2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
是的,有可能。
首先,您需要?jiǎng)?chuàng)建包含圖形名稱/文件名或您想要的標(biāo)識(shí)符的下拉列表,只需保留{'label': x, 'value': x}選項(xiàng)參數(shù)的結(jié)構(gòu)即可。label是您將在下拉列表中看到的內(nèi)容,value并將傳遞給回調(diào)(見下文)。
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
)])
接下來,您需要一個(gè)空白的 div(帶有id),其中將顯示繪圖:
fig_plot = html.Div(id='fig_plot')
現(xiàn)在創(chuàng)建一個(gè)回調(diào)。id='fig_dropdown'當(dāng)更改帶有 的輸入時(shí),value參數(shù)將傳遞給update_output函數(shù)。此函數(shù)的輸出將傳遞給傳遞給div的children參數(shù)。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)函數(shù)返回一個(gè)dcc.Graph()對(duì)象,其中包含您的圖形,具體取決于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)

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您的下拉框中有很多無花果可供選擇,可能需要對(duì)代碼進(jìn)行以下更改才能實(shí)現(xiàn):
@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')
添加回答
舉報(bào)