gpt4 book ai didi

python - 如何连接箱线图的中值

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:26 25 4
gpt4 key购买 nike

绘制连接箱线图平均值的线似乎是一件简单的事情,但我不知道如何在 pandas 中绘制此图。

我正在使用此语法来绘制箱线图,以便它自动生成 Y 与 X 设备的箱线图,而无需对数据框进行外部操作:

df.boxplot(column='Y_Data', by="Category", showfliers=True, showmeans=True)

enter image description here

我想到的一种方法是通过从箱线图中获取平均值来绘制线图,但我不确定如何从图中提取该信息。

最佳答案

您可以保存从 df.boxplot() 返回的轴对象,并使用同一轴将均值绘制为线图。我建议使用 Seaborn 的 pointplot对于线条,因为它可以很好地处理分类 x 轴。

首先让我们生成一些示例数据:

import pandas as pd
import numpy as np
import seaborn as sns

N = 150
values = np.random.random(size=N)
groups = np.random.choice(['A','B','C'], size=N)
df = pd.DataFrame({'value':values, 'group':groups})

print(df.head())
group value
0 A 0.816847
1 A 0.468465
2 C 0.871975
3 B 0.933708
4 A 0.480170
...

接下来,制作箱线图并保存坐标轴对象:

ax = df.boxplot(column='value', by='group', showfliers=True, 
positions=range(df.group.unique().shape[0]))

注意:Pyplot/Pandas boxplot() 中有一个奇怪的 positions 参数,它可能会导致差一错误。查看更多 this discussion ,包括我在这里采用的解决方法。

最后,使用 groupby 获取类别均值,然后将均值与覆盖在箱线图顶部的线图连接起来:

sns.pointplot(x='group', y='value', data=df.groupby('group', as_index=False).mean(), ax=ax)

boxplot

您的标题提到“中位数”,但您在帖子中谈论的是类别均值。我在这里使用手段;如果您想改为绘制中位数,请将 groupby 聚合更改为 median()

关于python - 如何连接箱线图的中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44039146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com