使用数据框中多个列的误差条来绘制条形图

时间:2019-07-23 20:04:38

标签: python pandas dataframe bar-chart errorbar

我正在尝试做一些应该很简单但无法通过其他类似问题找到答案的事情。我想绘制存储在数据框中的几组数据的条形图,同时也存储在数据框中的误差线值。

我有一个来自商业软件的数据框,该数据框具有多个列,我想将它们做成一个聚集的条形图,而我只能使用df.plot.bar()正确地进行处理。我现在遇到的问题只是我无法弄清楚如何从同一数据帧正确添加错误栏。

此代码可以很好地从样本数据以相同格式生成我想要的绘图类型:

df = pd.DataFrame()

#the groups can vary 
grp1 = 'a'
grp2 = 'b'
grp3 = 'c'

df['label'] = ['ID_1','ID_2','ID_3']
df[grp1+'_int'] = [5,5.5,6]
df[grp1+'_SD'] = [1,2,3]
df[grp2+'_int'] = [7,6,5]
df[grp2+'_SD'] = [2,1,1.5]
df[grp3+'_int'] = [6.5,5,5.5]
df[grp3+'_SD'] = [1.5,1.5,2]

ax = df.plot.bar(x='label', y=[grp1+'_int',grp2+'_int',grp3+'_int'])
plt.show()

如何从相应的* _SD列添加错误栏(仅正值可以,但实际上可以包含任何错误栏)?

编辑:问题似乎与实际数据框中的行数有关。这是一个有效和无效的测试代码的示例:

不起作用(引发ValueError:err必须为[标量| N,Nx1或2xN类数组]):

df = pd.DataFrame()

#the groups can vary 
grp1 = 'a'
grp2 = 'b'
grp3 = 'c'

df['label'] = ['ID_1','ID_2','ID_3','ID_4']
df[grp1+'_int'] = np.linspace(1,10,4)
df[grp1+'_SD'] = np.linspace(1,2,4)
df[grp2+'_int'] = np.linspace(2,8,4)
df[grp2+'_SD'] = np.linspace(1.5,3,4)
df[grp3+'_int'] = np.linspace(0.5,9,4)
df[grp3+'_SD'] = np.linspace(1,8,4)
print(df)
ax = df.plot.bar(x='label', y=[grp1+'_int',grp2+'_int',grp3+'_int'], yerr=df[[grp1+'_SD', grp2+'_SD', grp3+'_SD']].values)
plt.show()

工作:

df = pd.DataFrame()

#the groups can vary 
grp1 = 'a'
grp2 = 'b'
grp3 = 'c'

df['label'] = ['ID_1','ID_2','ID_3']
df[grp1+'_int'] = np.linspace(1,10,3)
df[grp1+'_SD'] = np.linspace(1,2,3)
df[grp2+'_int'] = np.linspace(2,8,3)
df[grp2+'_SD'] = np.linspace(1.5,3,3)
df[grp3+'_int'] = np.linspace(0.5,9,3)
df[grp3+'_SD'] = np.linspace(1,8,3)
print(df)
ax = df.plot.bar(x='label', y=[grp1+'_int',grp2+'_int',grp3+'_int'], yerr=df[[grp1+'_SD', grp2+'_SD', grp3+'_SD']].values)
plt.show()

1 个答案:

答案 0 :(得分:0)

已更新为添加T,以将yerr参数的np.array转置。

尝试一下:

df = pd.DataFrame()

#the groups can vary 
grp1 = 'a'
grp2 = 'b'
grp3 = 'c'

df['label'] = ['ID_1','ID_2','ID_3']
df[grp1+'_int'] = [5,5.5,6]
df[grp1+'_SD'] = [1,2,3]
df[grp2+'_int'] = [7,6,5]
df[grp2+'_SD'] = [2,1,1.5]
df[grp3+'_int'] = [6.5,5,5.5]
df[grp3+'_SD'] = [1.5,1.5,2]

ax = df.plot.bar(x='label', 
                y=[grp1+'_int',grp2+'_int',grp3+'_int'],
                yerr=df[['a_SD','b_SD','c_SD']].T.values)

输出:

enter image description here