我试图创建一个巧妙的破折号下拉,它的选择被用来过滤一个数据,并生成一个饼图从过滤的数据。我从巧妙的交互式可视化文档的工作代码开始,尽可能仔细地浏览并删除了所有额外的代码。(我只想要一个下拉列表和一个相似堆栈问题输出图)。
现在,我将继续讨论与代码的@app.callback
部分的逻辑有关的第一个问题。
@app.callback(
Output('indicator-graphic', 'figure'),
[Input('choose_species', 'value')])
输入标记是有意义的,因为上面有一个下拉列表,其中id
和value
等于Input
的参数。
html.Div([
dcc.Dropdown(
id='choose_species',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Pacific Water Shrew'
)
但是,尽管out有一个相关的id
dcc.Graph(id='indicator-graphic')
在带有文本figure
的代码中没有其他东西,我假设它必须来自函数update_graph
的输出,因为它在示例代码中被调用。在我自己的代码中没有提到任何其他的数字(这显然不起作用),在示例代码中也没有其他提到(考虑到我不知道如何工作,这确实让我感到惊讶)。
问题:
鉴于以上所述,如何将@app_callback
绑定到update-graph
函数。请记住,我对所有编码语言都很陌生。
发布于 2022-03-24 10:25:00
根据我的经验,你可以这样做:
app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([html.H5('Drop Down',className='text-center'),
dcc.Dropdown(
id='choose_species',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Pacific Water Shrew',
multi=True,
disabled=False,
clearable=True,
searchable=True),
dcc.Graph(id='indicator-graphic',figure={},style={'height':300,'width':'auto'})
])
@app.callback(Output('indicator-graphic', 'figure'),
[Input('choose_species', 'value')])
def build_graph(species):
fig = px.line(df,x='',y='',color='')
return fig
if __name__ == "__main__":
app.run_server(debug=False
)
您需要在布局中添加dcc.Graph
和figure={}
,而在@app.callback
下,您必须添加一个函数以在dropdown
过滤后返回figure
。
发布于 2022-03-24 03:48:13
figure
是Graph
的一部分,您可以在开始时向figure
传递值,如下所示
import dash
from dash import html, dcc
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Graph(figure={
'data': [{
'x': [1,2,3],
'y': [1,7,4],
}],
}
),
])
app.run_server()
但是,您也可以使用空的Graph
定义figure
。
import dash
from dash import html, dcc
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Graph(),
])
app.run_server()
稍后,您可以尝试将一些值赋值给figure
。
callback
的代码就是这样做的。
它使用id
访问Graph
,并分配给从callback
返回的figure
值。
当页面被加载时,它创建Dropdown
(用id='choose_species'
),并将'Pacific Water Shrew'
分配给value
,然后用[Input('choose_species', 'value')]
执行callback
,后者返回字典并回调,在Graph
和id='indicator-graphic'
中将其分配给figure
@
在@app.callback
中意味着它是装饰器,您必须将您的函数直接放在装饰器下面,以便将它分配给这个装饰器,或者更确切地说,是使用这个函数作为参数来执行这个装饰器。
import dash
from dash import html, dcc, Output, Input
# --- data ---
my_data = {
'Hello': {'x':[1,2,3], 'y': [1,7,4]},
'World': {'x':[1,2,3], 'y': [7,1,4]},
'Pacific Water Shrew': {'x':[1,2,3], 'y': [7,4,1]}
}
available_indicators = list(my_data.keys())
# --- HTML ---
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id='choose_species',
options=[{'label': i, 'value': i} for i in available_indicators],
value='Pacific Water Shrew'
),
dcc.Graph(id='indicator-graphic'),
])
# --- code ---
@app.callback(
Output('indicator-graphic', 'figure'),
[Input('choose_species', 'value')])
def update_graph(arg):
print('value from dropdown:', arg)
my_x = my_data[arg]['x']
my_y = my_data[arg]['y']
return {
'data': [dict(
x=my_x,
y=my_y,
)],
}
app.run_server()
https://stackoverflow.com/questions/71594970
复制相似问题