python - 在 Seaborn 和 Barplot 中使用预先计算的误差线

标签 python matplotlib seaborn

我有一个数据框,我在其中预先计算了一组特定值的平均值和标准差。数据框的片段及其创建方法如下所示:

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

channel = ["Red", "Green", "Blue", "Red", "Green", "Blue", "Red", "Green", "Blue"]
average= [83.438681, 36.512924, 17.826646, 83.763724, 36.689707, 17.892932, 84.747069, 37.072383, 18.070416]
sd = [7.451285, 3.673155, 1.933273, 7.915111, 3.802536, 2.060639, 7.415741, 3.659094, 2.020355]
conc = ["0.00", "0.00", "0.00", "0.25", "0.25", "0.25", "0.50", "0.50", "0.50"]

df = pd.DataFrame({"channel": channel,
                  "average": average,
                  "sd" : sd,
                  "conc": conc})

order = ["0.00", "0.25", "0.50"]
sns.barplot(x="conc", y="average", hue="channel", data=df, ci=None, order=order);

运行上面的代码会生成如下所示的图像:

enter image description here

我有一列 sd,它具有预先计算的标准偏差,我想在每个绘制的条形图的上方和下方添加误差条。但是我不知道该怎么做。

我们将不胜感激。

最佳答案

昨天遇到这个错误。在 seaborn 中,我相信你不能根据预先确定的错误添加错误栏。最简单的解决方案是在 seaborn 上绘制 matplotlib 条形图。

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

channel = ["Red", "Green", "Blue", "Red", "Green", "Blue", "Red", "Green", "Blue"]
average= [83.438681, 36.512924, 17.826646, 83.763724, 36.689707, 17.892932, 84.747069, 37.072383, 18.070416]
sd = [7.451285, 3.673155, 1.933273, 7.915111, 3.802536, 2.060639, 7.415741, 3.659094, 2.020355]
conc = ["0.00", "0.00", "0.00", "0.25", "0.25", "0.25", "0.50", "0.50", "0.50"]

df = pd.DataFrame({"channel": channel,
                  "average": average,
                  "sd" : sd,
                  "conc": conc})

order = ["0.00", "0.25", "0.50"]
sns.barplot(x="conc", y="average", hue="channel", data=df, ci=None, 
            order=order)


conc2=[0,0,0,1,1,1,2,2,2]
width = .25
add = [-1*width, 0 , width, -1*width, 0 , width, -1*width, 0 , width,]
x = np.array(conc2)+np.array(add)

plt.errorbar(x = x, y = df['average'],
            yerr=df['sd'], fmt='none', c= 'black', capsize = 2)
plt.show()

有点笨但是有用!

关于python - 在 Seaborn 和 Barplot 中使用预先计算的误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62820959/

相关文章:

python - Windows下调用shutil.copystat(file1, file2)后文件修改次数不相等

python - 在Python中导入RTree时如何修复 "ImportError: No module named index"?

matplotlib - plot 和 fill_between 的组合图例条目

python - 如何用渐变填充 matplotlib 条形图?

python - 在 Seaborn 中禁用色调嵌套

python - 有没有办法在 seaborn 点图中设置透明度/alpha 级别?

Python:替换字符串中的术语,除了最后一个

python - 直接保存时,Matplotlib 无法正确渲染曲线下的渐变

matplotlib - 我不知道如何制作一个新的 matplotlib 图

python - , 运算符用在条件语句的右侧时有何作用?