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

5

我将首先生成以下DataFrame,然后在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(即...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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接