【问题标题】:Return a graph based on a value from the dropdown根据下拉列表中的值返回图表
【发布时间】:2019-04-11 12:16:34
【问题描述】:

我正在尝试根据从下拉列表中选择的值绘制 matplotlib 图。我已经制作了下拉菜单,并且绘图也为值做好了准备,但我不知道如何将它们连接在一起。

以下是下拉菜单的代码:

app.layout = html.Div([
    dcc.Dropdown(
        id='first-dropdown',
        options = [
            {'label': 'Chest Pain', 'value': 'cp'},
            {'label': 'Resting Blood Pressure', 'value': 'trestbps'},
            {'label': 'Serum Cholestrol in mg/dl', 'value': 'chol'},
            {'label': 'Fasting Blood Pressure', 'value': 'fbs'},
            {'label': 'Resting electrocardiographic results', 'value': 'restecg'},
            {'label': 'Maximum heart rate achieved', 'value': 'thalach'},
            {'label': 'Exercise induced angina', 'value': 'exang'},
            {'label': 'Old Peak', 'value': 'oldpeak'},
            {'label': 'Slope of the peak exercise ST segment', 'value': 'slope'},
            {'label': 'Number of major vessels (0-3) colored by flourosopy', 'value': 'ca'},
            {'label': 'Thalassemia', 'value': 'thal'}
        ],
        value= 'thalach'
    )
])

对于下拉列表中的每个值,我都有一个单独的函数来返回一个绘图。例如: 我想要做的是,如果从下拉菜单中选择标签“达到的最大心率”,其值为“thalach”。我有一个名为 plotThalach 的函数,它返回如下图:

def plotThalach(df):
    df_men = df[df['sex'] == 1.0]
    df_women = df[df['sex'] == 0.0]
    plt.figure(figsize=(20, 8))
    plt.bar(df_men['age'] + 0.00, df_men['thalach'], color='b', width=0.25, label='Men')
    plt.bar(df_women['age'] + 0.25, df_women['thalach'], color='r', width=0.25, label='Women')
    plt.legend(loc='upper right')
    plt.xlabel("Age")
    plt.ylabel("Max Heart Rate")
    plt.title("Age vs Max Heart Rate")
    return plt

现在我如何连接这两者,当从下拉列表中选择一个值时,我的函数会被调用,并且绘图会显示在屏幕上。

【问题讨论】:

    标签: matplotlib plotly plotly-dash


    【解决方案1】:

    不清楚为什么要混合使用 plotly-dash 和 matplotlib,您可以使用 plotly-dash 轻松完成

    这是一个示例代码,

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output
    
    import pandas as pd
    import plotly.graph_objs as go
    
    df = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/'
        'datasets/master/gapminderDataFiveYear.csv')
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    
    
    
    #main div
    app.layout = html.Div([
    
        #drop down with a default value set
        dcc.Dropdown(
            id='xaxis-column',
            options=[{'label': str(year), 'value': year} for year in df['year'].unique()],
            value=df['year'].min(),
        ),
    
        #graph that is to be updated
        dcc.Graph(id='graph-with-slider')
    
    ])
    
    
    #callback which will be spawned when the input changes, in this case the input is the dropdown value
    @app.callback(
        Output('graph-with-slider', 'figure'),
        [Input('xaxis-column', 'value')])
    def update_figure(selected_year):
        filtered_df = df[df.year == selected_year]
        traces = []
        for i in filtered_df.continent.unique():
            df_by_continent = filtered_df[filtered_df['continent'] == i]
            traces.append(go.Scatter(
                x=df_by_continent['gdpPercap'],
                y=df_by_continent['lifeExp'],
                text=df_by_continent['country'],
                mode='markers',
                opacity=0.7,
                marker={
                    'size': 15,
                    'line': {'width': 0.5, 'color': 'white'}
                },
                name=i
            ))
    
        return {
            'data': traces,
            'layout': go.Layout(
                xaxis={'type': 'log', 'title': 'GDP Per Capita'},
                yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
                margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
                legend={'x': 0, 'y': 1},
                hovermode='closest'
            )
        }
    
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    

    但如果你想显示matplotlib 图表而不是 plotly-dash 图表,你可以参考“合并 Matplotlib 绘图”部分 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      相关资源
      最近更新 更多