Plotly Dash 下拉菜单 python

我想添加一个下拉菜单以仅显示一个数字。我的意思是,如果我选择无花果,破折号必须只显示无花果,如果我选择无花果 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)


小怪兽爱吃肉
浏览 216回答 2
2回答

达令说

是的,有可能。首先,您需要创建包含图形名称/文件名或您想要的标识符的下拉列表,只需保留{'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函数。此函数的输出将传递给传递给div的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 dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objects as go # or plotly.express as pxapp = 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)

FFIVE

如果您的下拉框中有很多无花果可供选择,可能需要对代码进行以下更改才能实现:@app.callback(Output('fig_plot', 'figure'), [Input('fig_dropdown', 'value')])def cb(plot_type):    plot_type = plot_type if plot_type else 'fig1'    df_year = head_db.copy()    if plot_type:        return px.bar(df_year, x='Week #', y=str(plot_type), color='Name')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python