python - 如何使用 plotly_express 创建线图,其中可以通过下拉菜单选择 pandas 数据框?
问题描述
我想创建一个线图,可以在其中通过下拉菜单选择基础数据。数据位于熊猫数据框中,我正在使用 plotly_express。
我试图以这篇文章为基础,但它不使用 plotly_express 并且数据不在 pandas 数据框中。
我有这段代码,我在其中定义了 a data1
,data2
然后将它们放入按钮中。我正在将这些数据帧转换为字典,因为如果不是,我将遇到数据帧不是“json-able”的错误。
# making two new dataframes out of the all-data dataframe (for drop down select)
dfe_deworming=dfe.loc['Deworming needed'].reset_index()
dfe_anemia=dfe.loc['Anemia'].reset_index()
# making the parameters for each button
#button 1
data1=dict(dfe_deworming)
x1=dfe_deworming.Month
y1=dfe_deworming.Count
color1=dfe_deworming.Facility
#button2
data2=dict(dfe_anemia)
x2=dfe_anemia.Month
y2=dfe_anemia.Count
color2=dfe_anemia.Facility
#initial plot
fig_deworming = px.line(data_frame=data1,x=x1,y=y1,color=color1)
# update menus
updatemenus = [
{
'buttons': [
{
'method': 'restyle',
'label': 'Deworming needed',
'args': [
{'data_frame':[data1],'x': [x1],'y':[y1],'color':[color1]},
]
},
{
'method': 'restyle',
'label': 'Anemia',
'args': [
{'data_frame':[data2],'x': [x2],'y':[y2],'color':[color2]},
]
}
],
'direction': 'down',
'showactive': True,
}
]
fig_deworming.update_layout(
updatemenus=updatemenus
)
fig_deworming.update_traces(mode='markers+lines')
fig_deworming.show()
在初始状态下,它看起来不错。但是,如果我尝试选择一个选项,所有行都会得到完全相同的数据集。它可能是所有不同数据集的组合。
这些图片说明了问题:
解决方案
基本上你需要使用图形对象参数结构来更新菜单
- 生成了一个似乎与您的结构匹配的数据框
- 使用plotly express创建图形
- 生成更新菜单,这些参数是您将传递给 go.Scatter 的参数
- 使用列表理解,因为每个菜单都是一样的
- 最终解决了plotly express生成的跟踪问题
hovertemplate
import numpy as np
import pandas as pd
import plotly.express as px
# generate a dataframe that matches structure in question
dfe = (
pd.DataFrame(
{
"Month": pd.date_range("1-jan-2020", freq="M", periods=50).month,
"Facility": np.random.choice(["Deworming needed", "Anemia"], 50),
"Count": np.random.randint(5, 20, 50),
}
)
.groupby(["Facility", "Month"], as_index=False)
.agg({"Count": "sum"})
)
# the line plot with px...
fig = px.line(
dfe.loc[dfe.Facility.eq("Deworming needed")], x="Month", y="Count", color="Facility"
)
# fundametally need to be working with graph object parameters not express parameters
updatemenus = [
{
"buttons": [
{
"method": "restyle",
"label": f,
"args": [
{
"x": [dfe.loc[dfe.Facility.eq(f), "Month"]],
"y": [dfe.loc[dfe.Facility.eq(f), "Count"]],
"name": f,
"meta": f,
},
],
}
for f in ["Deworming needed", "Anemia"] # dfe["Facility"].unique()
],
"direction": "down",
"showactive": True,
}
]
fig = fig.update_layout(updatemenus=updatemenus)
# px does not set an appropriate hovertemplate....
fig.update_traces(
hovertemplate="Facility=%{meta}<br>Month=%{x}<br>Count=%{y}<extra></extra>",
meta="Deworming needed",
)
推荐阅读
- arrays - 使用 np.where 子集 3d 数组
- groovy - Groovy 多值哈希映射
- mongodb - 获取字符串日期之间的数据 MongoDB
- python - Python Pandas 正则表达式特定字符串
- python - 带有 SQLAlchemy 的 urllib request.urlopen(url).read() 存储的是十六进制字符串而不是 HTML
- drools - 当问题与 .drl 'or' 子句相关时,是什么原因导致 ConstraintMatchTotal 无法添加约束匹配?
- django - 如何为未经授权的用户禁用(几乎)所有表单中的所有字段?
- sql - 在 CATCH 块中记录错误后如何继续执行存储过程
- swift - 有什么方法可以在 Swift 中检测形状轮廓而无需扩展到 OpenCV?
- asp.net-core - 为什么此 Blazor 应用程序中的组件无法呈现?