我有下面的数据框,我想绘制“关闭”/“打开”状态的堆积条形图。
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
最佳答案
既然你提到了pandas的pivot函数 - you can transform your dataset with it在堆叠条形图之前在一行中:
df_temp.pivot(columns = "state", values = "requests").plot(kind = "bar", stacked = True)
现在我们还可以美化图表 - 标记 y 轴,旋转 x 刻度标签:
plt.ylabel("Requests")
plt.xticks(rotation = 45, ha = "right")
plt.tight_layout()
plt.show()
关于python - Pandas : plot stacked barchart for row values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51042113/