gpt4 book ai didi

python - 如何在 Pandas 列的分组条形图上添加误差线

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

我有一个 具有四列的数据框 df:CandidateSample_SetValues错误Candidate 列具有三个独特的条目:[X, Y, Z] 并且我们有三个样本集,因此 Sample_Set 具有还有三个唯一值:[1,2,3]。 df 大致如下所示。

import pandas as pd

data = {'Candidate': ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z'],
'Sample_Set': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'Values': [20, 10, 10, 200, 101, 99, 1999, 998, 1003],
'Error': [5, 2, 3, 30, 30, 30, 10, 10, 10]}
df = pd.DataFrame(data)

# display(df)
Candidate Sample_Set Values Error
0 X 1 20 5
1 Y 1 10 2
2 Z 1 10 3
3 X 2 200 30
4 Y 2 101 30
5 Z 2 99 30
6 X 3 1999 10
7 Y 3 998 10
8 Z 3 1003 10

我正在使用 使用 x="Candidate"y="Values"hue="Sample_Set" 从中创建一个分组条形图。一切都很好,直到我尝试使用名为 Error 的列下的值沿 y 轴添加错误栏。我正在使用以下代码。

import seaborn as sns

ax = sns.factorplot(x="Candidate", y="Values", hue="Sample_Set", data=df,
size=8, kind="bar")

如何合并错误?

我会很感激这个任务的解决方案或更优雅的方法。

最佳答案

正如@ResMar 在评论中指出的那样,seaborn 中似乎没有内置功能可以轻松设置单个错误栏。

如果您更关心结果而不是到达那里的方式,以下(不是那么优雅)解决方案可能会有所帮助,它构建于 matplotlib.pyplot.bar 之上。 seaborn 导入只是用来获取相同的样式。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

def grouped_barplot(df, cat,subcat, val , err):
u = df[cat].unique()
x = np.arange(len(u))
subx = df[subcat].unique()
offsets = (np.arange(len(subx))-np.arange(len(subx)).mean())/(len(subx)+1.)
width= np.diff(offsets).mean()
for i,gr in enumerate(subx):
dfg = df[df[subcat] == gr]
plt.bar(x+offsets[i], dfg[val].values, width=width,
label="{} {}".format(subcat, gr), yerr=dfg[err].values)
plt.xlabel(cat)
plt.ylabel(val)
plt.xticks(x, u)
plt.legend()
plt.show()


cat = "Candidate"
subcat = "Sample_Set"
val = "Values"
err = "Error"

# call the function with df from the question
grouped_barplot(df, cat, subcat, val, err )

enter image description here

注意通过简单的反转类别和子类别

cat = "Sample_Set"
subcat = "Candidate"

你可以得到不同的分组:

enter image description here

关于python - 如何在 Pandas 列的分组条形图上添加误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42017049/

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