简体   繁体   English

如何使用 plotly_express 创建一条线 plot,其中可以通过下拉菜单选择 pandas dataframe?

[英]How can I create a line plot with plotly_express, where a pandas dataframe can be selected over a drop down menu?

I want to create a line plot in which the underlying data can be selected over a drop down menu.我想创建一行 plot ,其中可以通过下拉菜单选择基础数据。 The data is in a pandas dataframe and I am using plotly_express.数据在 pandas dataframe 中,我正在使用 plotly_express。

I tried to use this post as a basis but it does not use plotly_express and the data is not in a pandas dataframe.我试图以这篇文章为基础,但它不使用 plotly_express 并且数据不在 pandas dataframe 中。

I have this code in which I define a data1 and data2 and then put those into the buttons.我有这段代码,我在其中定义了一个data1data2 ,然后将它们放入按钮中。 I am converting those dataframes into a dictionnary because if not I will have the error that dataframes were not "json-able".我正在将这些数据帧转换为字典,因为如果不是,我将遇到数据帧不是“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()

In its initial state it looks good.在其最初的 state 中看起来不错。 However if I try to select an option, all lines get exactly the same dataset.但是,如果我尝试使用 select 选项,所有行都会得到完全相同的数据集。 It could be the combination of all the different datasets.它可能是所有不同数据集的组合。

Those pictures illustrate the problem:这些图片说明了问题:

First option of the drop down menu after first selection第一次选择后下拉菜单的第一个选项

Second option of the drop down menu after second selection第二次选择后下拉菜单的第二个选项

fundamentally you need to use graph object parameter structure for updatemenus基本上你需要使用graph object参数结构来更新菜单

  • have generated a dataframe that appears to match your structure已生成 dataframe 似乎与您的结构匹配
  • create the graph using plotly express使用plotly express创建图形
  • generate updatemenu which are parameters you would pass to go.Scatter生成更新菜单,这些参数是您将传递给 go.Scatter参数
  • used a list comprehension as each menu is really the same使用列表理解,因为每个菜单都是一样的
  • finally fix an issue with trace generated by plotly express for hovertemplate最终解决了plotly expresshovertemplate生成的跟踪问题
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",
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM