我想添加一个下拉菜单,只显示一个数字。我的意思是,如果我选择无花果,仪表盘必须只显示无花果,如果我选择无花果2,仪表盘必须显示无花果2。我的代码是一个例子,我有超过500个无花果,我想添加一个下拉菜单。
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure()
fig2 = go.Figure()
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"))
fig2.add_trace(go.Bar(y=[2, 1, 3]))
figs = [fig, fig2]
div = []
for item in figs:
div.append(dcc.Graph(figure=item))
app = dash.Dash()
app.layout = html.Div(div)
"""
add a dropdown to show only one fig
"""
app.run_server(debug=True, use_reloader=False)
是的,这是可能的。
首先,你需要创建一个下拉菜单,其中包含图名文件名或你想要的标识符,只需保持这个下拉菜单中的 {'label': x, 'value': x}
结构的选项参数。label
是您在下拉菜单中看到的内容,而 value
将被传递给回调(如下)。
fig_names = ['fig1', 'fig2']
fig_dropdown = html.Div([
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
)])
接下来,你需要一个空白的div(有一个 id
),在那里将出现情节。
fig_plot = html.Div(id='fig_plot')
现在创建一个回调。当输入带有 id='fig_dropdown'
变化的情况下 value
参数将被传递给 update_output
函数,该函数的输出将被传递给 该函数的输出将被传递给传递给 children
参数的 id='fig_plot'
鸿沟
@app.callback(
dash.dependencies.Output('fig_plot', 'children'),
[dash.dependencies.Input('fig_dropdown', 'value')])
def update_output(fig_name):
return name_to_figure(fig_name)
该 name_to_figure(fig_name)
函数返回一个 dcc.Graph()
对象,包含您的人物,取决于 fig_name
下拉菜单的值。
完整的例子:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go # or plotly.express as px
app = dash.Dash()
fig_names = ['fig1', 'fig2']
fig_dropdown = html.Div([
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
)])
fig_plot = html.Div(id='fig_plot')
app.layout = html.Div([fig_dropdown, fig_plot])
@app.callback(
dash.dependencies.Output('fig_plot', 'children'),
[dash.dependencies.Input('fig_dropdown', 'value')])
def update_output(fig_name):
return name_to_figure(fig_name)
def name_to_figure(fig_name):
figure = go.Figure()
if fig_name == 'fig1':
figure.add_trace(go.Scatter(y=[4, 2, 1]))
elif fig_name == 'fig2':
figure.add_trace(go.Bar(y=[2, 1, 3]))
return dcc.Graph(figure=figure)
app.run_server(debug=True, use_reloader=False)