簡體   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?

我想創建一行 plot ,其中可以通過下拉菜單選擇基礎數據。 數據在 pandas dataframe 中,我正在使用 plotly_express。

我試圖以這篇文章為基礎,但它不使用 plotly_express 並且數據不在 pandas dataframe 中。

我有這段代碼,我在其中定義了一個data1data2 ,然后將它們放入按鈕中。 我正在將這些數據幀轉換為字典,因為如果不是,我將遇到數據幀不是“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()

在其最初的 state 中看起來不錯。 但是,如果我嘗試使用 select 選項,所有行都會得到完全相同的數據集。 它可能是所有不同數據集的組合。

這些圖片說明了問題:

第一次選擇后下拉菜單的第一個選項

第二次選擇后下拉菜單的第二個選項

基本上你需要使用graph object參數結構來更新菜單

  • 已生成 dataframe 似乎與您的結構匹配
  • 使用plotly express創建圖形
  • 生成更新菜單,這些參數是您將傳遞給 go.Scatter參數
  • 使用列表理解,因為每個菜單都是一樣的
  • 最終解決了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