【问题标题】:Adding error bars to grouped bar plot in pandas将误差线添加到熊猫中的分组条形图中
【发布时间】:2014-05-24 21:22:20
【问题描述】:

我通过首先生成以下 DataFrame 在 pandas 中生成图:

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

生成的数据框如下所示:

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

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

结果如下:

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

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:
    • 绘制分组条和相应的误差条取决于所传递的数据框的形状。
    • 使用.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)
    

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

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 2019-05-03
      • 2014-05-02
      • 2016-01-04
      • 2020-10-22
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多