在pandas中为分组条形图添加误差条

5 投票
1 回答
8526 浏览
提问于 2025-04-18 02:17

我在用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

然后我进行了数据透视和绘图,像这样:

plotData.pivot(index='student_model',columns='lo_id',values='mean').plot(kind='bar')

结果是这样的:

enter image description here

这都没问题,但我需要把“se”这一列的数值作为误差条添加到图表中,但我不知道怎么做。我知道可以在绘图时添加一个参数(比如 ...plot(kind='bar', yerr=???)),但我不太清楚该怎么格式化才能让它正常工作。有没有什么想法?

1 个回答

16
  • 绘制分组柱状图和相应的误差条,取决于你传入的数据框的形状。
  • 使用 .pivot 来调整数据框的形状,以便与 yerr 一起使用。
  • 一个重要的要求是,当你把 yerr 作为数据框传入时,列名必须和柱状图使用的列名一致。如果列名不一样,误差条就不会显示出来。
  • python 3.8.11pandas 1.3.3matplotlib 3.4.3 中测试过
import pandas as pd

# dataframe
data = {'class1': ['A', 'A', 'B', 'B'], 'class2': ['R', 'G', 'R', 'G'], 'se': [1, 1, 1, 1], 'val': [1, 2, 3, 4]}
df = pd.DataFrame(data)

  class1 class2  se  val
0      A      R   1    1
1      A      G   1    2
2      B      R   1    3
3      B      G   1    4

# pivot the data
dfp = df.pivot(index='class1', columns='class2', values='val')

class2  G  R
class1      
A       2  1
B       4  3

# pivot the error
yerr = df.pivot(index='class1', columns='class2', values='se')

class2  G  R
class1      
A       1  1
B       1  1

# plot
dfp.plot(kind='bar', yerr=yerr, rot=0)

enter image description here

  • 可选项
# 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 as generalized

撰写回答