使用下拉菜单连接图表(Plotly Dash)

Connecting graphs with dropdown (Plotly Dash)

我正在构建应用程序,我想在其中绘制来自两个数据框的两个单独的图形。我想使用下拉菜单根据每个数据框 (df,df1) 每页只显示一个图表。 我遵循了 Plotly 参考资料,但无法在我的示例中重现它。 到目前为止,这是我的代码(它在同一页面上显示两个图表,没有下拉菜单):

import pandas as pd
import dash
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

data = [['Blue',20],['Red ',12],['Green',33]]
df = pd.DataFrame(data,columns=['Color','Number'])

data1 = [['A',10,88],['B ',50,45],['C',25,120]]
df1 = pd.DataFrame(data1,columns=['Letter','Column1','Column2'])

fig = px.bar(df, x=df['Color'], y=df['Number'])
fig1 = px.line(x=df1['Letter'], y=df1['Column1'], color=px.Constant('Column1'),
             labels=dict(x='Letter', y='Column1', color='Letter'))
fig1.add_bar(x=df1['Letter'], y=df1['Column2'], name='Letter')

app.layout = html.Div(children=[
    html.H1(children='Colors and Letters', style={'text-align': 'center'}),

     html.Div(children='Color', style={'text-align': 'center'}),

    dcc.Graph(
        id='example-graph',
        figure=fig
    ),
    html.Div(children='Letter', style={'text-align': 'center'}),

    dcc.Graph(
        id='example-graph1',
        figure=fig1
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

这是我想要得到的:

执行此操作的最佳方法是什么? 提前致谢。

我对 Dash 没有太多经验,但这里有很棒的 和您的代码。重点是引入下拉菜单,以便初始值显示为图。根据回调函数的return值,我使用if函数切换图

import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

data = [['Blue',20],['Red ',12],['Green',33]]
df = pd.DataFrame(data,columns=['Color','Number'])

data1 = [['A',10,88],['B ',50,45],['C',25,120]]
df1 = pd.DataFrame(data1,columns=['Letter','Column1','Column2'])

app.layout = html.Div(children=[
    html.H1(children='Colors and Letters', style={'text-align': 'center'}),
    html.Div(children='Color', style={'text-align': 'center'}),

    html.Div([
        html.Label(['Choose a graph:'],style={'font-weight': 'bold'}),
        dcc.Dropdown(
            id='dropdown',
            options=[
                {'label': 'graph1', 'value': 'graph1'},
                {'label': 'graph2', 'value': 'graph2'},
                    ],
            value='graph1',
            style={"width": "60%"}),
        
    html.Div(dcc.Graph(id='graph')),        
        ]),

])

@app.callback(
    Output('graph', 'figure'),
    [Input(component_id='dropdown', component_property='value')]
)
def select_graph(value):
    if value == 'graph1':
        fig = px.bar(df, x=df['Color'], y=df['Number'])
        return fig
    else:
        fig1 = px.line(x=df1['Letter'], y=df1['Column1'], color=px.Constant('Column1'),
                     labels=dict(x='Letter', y='Column1', color='Letter'))
        fig1.add_bar(x=df1['Letter'], y=df1['Column2'], name='Letter')
        return fig1
    
if __name__ == '__main__':
    app.run_server(debug=True)