matplotlib - 根据下拉列表中的值返回图表
问题描述
我正在尝试根据从下拉列表中选择的值绘制 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
现在我如何以这样的方式连接这两者,当从下拉列表中选择一个值时,我的函数被调用并绘图显示在屏幕上。
解决方案
目前还不清楚为什么要混合使用 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)
但是,如果您想显示图形而不是 plotly-dash 图,您可以参考此处matplotlib
的“合并 Matplotlib 绘图”部分
推荐阅读
- reactjs - 导航到组件时声明为接口的道具不可用
- python - Django 不显示验证错误
- mysql - 如何从 cmd 执行 sql 转储以从旧 xampp 导出数据库
- node.js - EACCES:仅使用 nodemon 拒绝 fs-extra 的权限
- gcc - 如何使用 CMake 在 AIX 上生成 *.so 文件
- angular - 无法绑定到“ngForOf”,因为它不是“li”的已知属性
- javascript - 使用 Javascript 将 H1 标签更改为 H2
- google-kubernetes-engine - 是否可以通过 L4 LB 与 GKE 直接连接 grpc 客户端而不使用 ESP?
- r - R中的ggplot - 带有颜色分割图块的geom_tile
- firebase - 如何在 React Native Firebase 中检查好友的存在