【发布时间】:2018-06-26 11:44:11
【问题描述】:
我有以下数据框,我想为“关闭”/“打开”状态绘制堆积条形图。
state requests
created
2016-09-28 OPEN 1
2017-02-03 OPEN 1
2017-06-15 CLOSED 1
2017-06-15 OPEN 1
2017-06-16 CLOSED 2
2017-08-23 OPEN 1
2017-10-25 OPEN 1
2018-01-19 OPEN 1
2018-03-01 OPEN 1
2018-03-05 OPEN 1
2018-06-12 OPEN 1
2018-06-15 OPEN 1
我尝试了以下(df_temp 是上述数据的数据框)
fig,ax = plt.subplots()
ax.set_ylabel('Requests')
df_closed = df_temp[df_temp['state'] == 'CLOSED']
df_open = df_temp[df_temp['state'] == 'OPEN']
b = ax.bar(x = df_open.index.get_level_values(0), height = df_open['requests'])
a = ax.bar(x = df_closed.index.get_level_values(0), height = df_closed['requests'],bottom = df_open['requests'])
但它给了我错误
ValueError: shape mismatch: objects cannot be broadcast to a single shape
编辑:
解决方案 Marco 建议可行,但如果有很多“状态”怎么办。例如,如果有 10 个不同的状态,那么我们可以通过循环或其他方式绘制它。我寻找了其他使用 pivot_table 和 unstack() 的问题,我不知道如何在这里使用它。
【问题讨论】:
-
您可以在这里查看:matplotlib.org/examples/pylab_examples/bar_stacked.html。也就是说,首先你应该绘制两个中的一个(例如
ax.bar(df_closed.index, df_closed.requests)),然后通过指定它应该从上面开始另一个(例如ax.bar(df_open.index, df_open.requests, bottom=df_closed.requests)。编辑:你应该首先确保它们具有相同的索引,例如@987654327 @,其中“...”是两组索引的并集。 -
@MarcoSpinaci,感谢您的回复,它有效,但如果“状态”列值未知怎么办。假设有 10 种不同的状态,那么我们有什么方法可以通过循环或其他方式来实现吗?
-
是的,我可能会做一个 for 循环,类似于
for s in df.state.unique(),并在每一步更新一个“底部”系列,说明我们到目前为止添加了多少。
标签: python python-3.x pandas matplotlib