根据下拉列表中的值返回图形

时间:2019-04-11 12:16:34

标签: matplotlib plotly plotly-dash

我试图根据从下拉列表中选择的值绘制一个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

现在我该如何连接这两种方法,以便从下拉列表中选择一个值时,将调用我的函数,并在屏幕上显示绘图。

1 个答案:

答案 0 :(得分:0)

尚不清楚为什么要混合使用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图而不是散点图,则可以参考“合并Matplotlib图”一节here