在pandas中将误差线添加到分组条形图中

2024-06-26 14:05:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过首先生成以下数据帧在pandas中生成一个图:

plotData=resultData.groupby(['student_model','lo_id']).describe().nShots.unstack().reset_index()
plotData['se'] = plotData['std']/np.sqrt(plotData['count'])

生成的数据帧如下所示: enter image description here

然后我就这样旋转和绘制:

^{pr2}$

结果如下:

enter image description here

没关系,但我需要将“se”列中的值作为errorbars添加到绘图中,但无法使其正常工作。我知道我可以添加一个参数来调用plot(即...plot(kind='bar', yerr=???)),但我不知道如何正确格式化它,使其正常工作。有什么想法吗?在


Tags: 数据idlopandasmodelplotstudentreset
1条回答
网友
1楼 · 发布于 2024-06-26 14:05:10

以图片形式发布数据不是一个好主意。这里有一个解决方案:

In [16]:
#se column store the errorbar values
print df
  class1 class2  se  val
0      A      R   1    1
1      A      G   1    2
2      B      R   1    3
3      B      G   1    4

[4 rows x 4 columns]
In [17]:

df.pivot(index='class1',columns='class2',values='val').plot(kind='bar', yerr=df.pivot(index='class1',columns='class2',values='se').values)
#or yerr=df.se.reshape((2,2))
#Where (2,2) is the shape of df.pivot(index='class1',columns='class2',values='val')
#which is less verbose but may not be general

enter image description here

相关问题 更多 >