Python 用多个条绘制。如何修复?
我有一个数据帧,数据非常不均匀,如下所示:Python 用多个条绘制。如何修复?,python,pandas,matplotlib,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
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()
因此,我得到如下smth:
以及错误索引器错误:列表索引超出了指向plt.legend()的链接的范围。我做错了什么?要获得正常打印输出,我应该纠正什么?IIUC,您可以执行以下操作:
for date, data in df.groupby('Date'):
print(data)
(data.groupby(['Obj','Feature'])['FeatureValue'].mean()
.unstack('Feature').plot.bar())