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

问题描述 投票:0回答:1

我试图根据从下拉列表中选择的值绘制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个回答
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图而不是plotly-dash图,你可以参考“合并Matplotlib图”部分here

© www.soinside.com 2019 - 2024. All rights reserved.