【问题标题】:Change Plotly Boxplot Hover Data更改绘图箱线图悬停数据
【发布时间】:2021-10-22 01:08:02
【问题描述】:

我想更改 python plotly boxplot 的悬停文本和悬停数据。我想要一个用于中位数、平均值、IQR 和日期的浓缩悬停框,而不是 5 个单独的悬停框用于最大值、q3、中值、q1 和最小值。我玩弄了每个“悬停”变量,但没有运气。下面是我的示例代码。

import numpy as np
import plotly.express as px

lst = [['2020'], ['2021']] 
numbers = [20 , 25]
r = [x for i, j in zip(lst, numbers) for x in i*j]

df = pd.DataFrame(r, columns=['year'])
df['obs'] = np.arange(1,len(df)+1) * np.random.random()

mean = df.groupby('year').mean()[['obs']]
median = df.groupby('year').median()[['obs']]
iqr = df.groupby('year').quantile(0.75)[['obs']] - df.groupby('year').quantile(0.25)[['obs']]

stats = pd.concat([mean,median,iqr], axis=1)
stats.columns = ['Mean','Median','IQR']
tot_df = pd.merge(df,stats, right_index=True, left_on='year', how = 'left')

fig = px.box(tot_df, x="year", y="obs", points=False, hover_data=['year','Mean','Median','IQR'])
fig.show()

在这种情况下,我尝试使用“hover_data”,它不会引发错误,但也不会改变绘图,如上所示。我试过 express 和 graph_objects 都没有运气。我的情节版本是 4.9.0。谢谢!

【问题讨论】:

    标签: python statistics plotly visualization boxplot


    【解决方案1】:
    • 使用了在 boxplot 轨迹上叠加 bar 轨迹的技术
    • bar 可以配置跟踪以显示您想要的信息
    • 为了演示,我将opacity设置为0.05,可以设置为0使其完全不可见
    • 已针对 plotly 5.2.1 构建此功能,尚未针对 4.9.0 进行测试
    import numpy as np
    import plotly.express as px
    import pandas as pd
    
    lst = [['2020'], ['2021']] 
    numbers = [20 , 25]
    r = [x for i, j in zip(lst, numbers) for x in i*j]
    
    df = pd.DataFrame(r, columns=['year'])
    df['obs'] = np.arange(1,len(df)+1) * np.random.random()
    
    mean = df.groupby('year').mean()[['obs']]
    median = df.groupby('year').median()[['obs']]
    iqr = df.groupby('year').quantile(0.75)[['obs']] - df.groupby('year').quantile(0.25)[['obs']]
    
    stats = pd.concat([mean,median,iqr], axis=1)
    stats.columns = ['Mean','Median','IQR']
    tot_df = pd.merge(df,stats, right_index=True, left_on='year', how = 'left')
    
    fig = px.box(tot_df, x="year", y="obs", points=False)
    
    fig2 = px.bar(
        tot_df.groupby("year", as_index=False)
        .agg(base=("obs", "min"), bar=("obs", lambda s: s.max() - s.min()))
        .merge(
            tot_df.groupby("year", as_index=False).agg(
                {c: "first" for c in tot_df.columns if c not in ["year", "obs"]}
            ),
            on="year",
        ),
        x="year",
        y="bar",
        base="base",
        hover_data={
            **{c: True for c in tot_df.columns if c not in ["year", "obs"]},
            **{"base": False, "bar": False},
        },
    ).update_traces(opacity=0.05)
    
    fig.add_traces(fig2.data)
    

    fig2 没有命名聚合

    fig2 = px.bar(
        tot_df.groupby("year", as_index=False)["obs"]
        .apply(lambda s: pd.Series({"base": s.min(), "bar": s.max() - s.min()}))
        .merge(
            tot_df.groupby("year", as_index=False).agg(
                {c: "first" for c in tot_df.columns if c not in ["year", "obs"]}
            ),
            on="year",
        ),
        x="year",
        y="bar",
        base="base",
        hover_data={
            **{c: True for c in tot_df.columns if c not in ["year", "obs"]},
            **{"base": False, "bar": False},
        },
    ).update_traces(opacity=0.05)
    
    

    【讨论】:

    • 我的 pandas 版本是 0.24.2,因此,这个 groupby 命名聚合的实现不起作用。鉴于,我不确定为 px.bar 的第一个参数构造了什么,您能否建议如何更改此 groupby 语句以与 pandas 0.24.2 兼容?谢谢。
    • 这是 pandas 的一个古老版本,名为聚合pandas-docs.github.io/pandas-docs-travis/whatsnew/v0.25.0.html 是在 0.25 中引入的。我不能降级到 0.24.2,因为轮子不会建立在我的环境中。您能否将 pandas 升级到不到 2 年的版本?
    • 已经用另一种构建 fig2 的方式更新了答案,没有命名聚合。我无法验证这是否适用于旧版 pandas
    猜你喜欢
    • 2022-01-03
    • 2020-11-05
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2017-12-16
    • 1970-01-01
    相关资源
    最近更新 更多