用多个条形图。怎么修?

时间:2019-10-30 22:12:38

标签: python pandas matplotlib

我有一个数据帧,数据看起来很不均匀,像这样:

    Date      | Obj  | Feature | FeatureValue |  
    2019-08-28| DT1  |   foo   |     15       |  
    2019-08-28| DT1  |   bar   |     25       |  
    2019-08-28| DT1  |   baz   |     70       |  
    2019-08-28| DT2  |   foo   |     45       |  
    2019-08-28| DT2  |   baz   |     67       |  
    2019-08-28| DT3  |   foo   |     78       |  
    2019-08-28| DT3  |   bar   |     19       |  
    2019-08-29| DT1  |   foo   |     12       |  
    2019-08-29| DT1  |   bar   |     45       |  
    2019-08-30| DT2  |   foo   |     19       |  
    2019-08-30| DT2  |   bar   |     23       |  
    2019-08-30| DT3  |   foo   |     23       |  
    2019-08-30| DT3  |   baz   |     34       |  

我的目标是绘制每个日期的图,其中X轴是OBJ,Y是-特征值,而条形-特征。

所以我做到了:

df = pd.DataFrame(np.array([['2019-08-28', 'DT1', 'foo' ,15], ['2019-08-28', 'DT1', 'bar',25],
                            ['2019-08-28', 'DT1', 'baz', 70], ['2019-08-28', 'DT2', 'foo', 45],   
                            ['2019-08-28', 'DT3', 'baz', 67], ['2019-08-28', 'DT3', 'foo', 78],   
                            ['2019-08-28', 'DT3', 'bar', 19], ['2019-08-29', 'DT1', 'foo', 12],   
                            ['2019-08-28', 'DT1', 'bar', 45], ['2019-08-30', 'DT2', 'foo', 19],   
                            ['2019-08-30', 'DT2', 'bar', 23], ['2019-08-30', 'DT3', 'foo', 23],   
                            ['2019-08-30', 'DT3', 'baz', 34]]),  
                           columns=['Date', 'Obj', 'Feature', 'FeatureValue'])

for date in df.Date.unique():
    DDD = df[df['Date'] == date]
    X = DDD.Obj.unique()
    for obj in X:
        y1 = np.array(DDD[DDD['Obj'] == obj][DDD['Feature']=='foo']['FeatureValue'].values)
        y2 = np.array(DDD[DDD['Obj'] == obj][DDD['Feature']=='bar']['FeatureValue'].values)
        y3 = np.array(DDD[DDD['Obj']==obj][DDD['Feature']=='baz']['FeatureValue'].values)
        width=0.4
        fig, ax = plt.subplots()
        try:
            ax.bar(X, y1, width, color='#000080', label='AC')
            ax.bar(X, width, y2, width, color='#0F52BA', label ='Cell (alarm)')
            ax.bar(X, 2*width, y3, width, color='#6593F5', label='Cell (manual)')
        except:
            pass
        ax.set_title(date)
        ax.legend()
        plt.show()  

结果我得到了这样的信息:

enter image description here

和错误IndexError:列出了超出范围的索引,并带有指向plt.legend()的链接。我怎么了我应该如何纠正才能获得法线图输出?

1 个答案:

答案 0 :(得分:1)

IIUC,您可以这样做:

for date, data in df.groupby('Date'):
    print(data)
    (data.groupby(['Obj','Feature'])['FeatureValue'].mean()
        .unstack('Feature').plot.bar())