python - Pandas : plot stacked barchart for row values

标签 python python-3.x pandas matplotlib

我有下面的数据框,我想绘制“关闭”/“打开”状态的堆积条形图。

             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/

相关文章:

python - 在python中使用bs4从网站的不同链接获取律师详细信息

python - 无法在装饰器中捕获 pytest 的结果

python - 根据列的组合增加列值

python - Pandas groupby、loc、forloop 和条件语句

Python 子进程 : Print to stdin, 读取标准输出直到换行,重复

python - 使用带有 for 循环的字典来比较值

python - Pandas/numpy 加权平均 ZeroDivisionError

python - 过滤 Django 时保持带注释的排名

python - 向量化前瞻性函数 pandas 数据框

python-3.x - Telethon 在 python 中的第一步