【发布时间】:2021-11-15 17:44:39
【问题描述】:
我正在做一些 GIS 分析,有点慌张。
我需要创建一个交互式绘图仪表板应用程序,其中您有两个多下拉仪表板核心组件,它们更新 px.scatter_mapbox 地图上的值。 DataFrame 在下拉列表中有以下我需要的“过滤器”/字段:种族/民族和城市。我被困在这一点上:
- 点击 Race Drop down (Multi) (works)
- 城市选项已适当填写(有效)
- 地图不会更新 - 只会返回您在下面看到的内容。
这是我的代码:
import dash.dependencies
import plotly.express as px
import pandas as pd
from jupyter_dash import JupyterDash
import dash_core_components as dcc
from dash import html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
px.set_mapbox_access_token(mapbox_access_token)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
re_indicators = df["RE"].unique()
city_indicators = df["CITY"].unique()
app.layout = html.Div([
html.Div(children=[
html.Label('Race & Ethnicity'),
dcc.Dropdown( id = "re",
options=[{'label': i, 'value': i} for i in re_indicators],
value = ["White"],
multi = True
),
html.Label('City'),
dcc.Dropdown( id = "city",
options=[],
value = [],
multi = True
),
html.Div([
dcc.Graph(
id='my_map',
figure = {})
])
])])
@app.callback(
dash.dependencies.Output('city', 'options'),
dash.dependencies.Input('re', 'value')
)
def re_picker(choose_re):
if len(choose_re) > 0:
dff = df[df.RE.isin(choose_re)]
return [{'label': i, 'value': i} for i in (dff.CITY.unique())]
@app.callback(
dash.dependencies.Output('city', 'value'),
dash.dependencies.Input('city', 'options')
)
def set_city_value(available_options):
return [x['value'] for x in available_options]
@app.callback(
dash.dependencies.Output('my_map', 'figure'),
[dash.dependencies.Input('re', 'value'),
dash.dependencies.Input('city', 'value')]
)
def update_figure(selected_re, selected_city):
if len(selected_re) == 0:
return print("nope")
else:
df_filtered = dff[(dff['CITY'] == selected_city)]
fig = px.scatter_mapbox(df_filtered,
lat="Latitude",
lon="Longitude",
zoom=1)
return fig
# Run app and display result inline in the notebook
if __name__ == '__main__':
app.run_server(host = "127.0.0.1", port = "8888", mode= "inline", debug = False)
【问题讨论】:
-
由于您没有共享数据,我无法完全重现该问题,但我猜该错误来自这一行:
dff['CITY'] == selected_city。尝试用dff['CITY'] .isin(selected_city)替换它。请注意,selected_city是一个列表,因为它是一个多下拉列表的值。 -
真的需要一些样本数据,我可以在 kaggle 上按国家/地区找到人口统计数据,但按城市却找不到
标签: python plotly-dash plotly-python