如何在 Pandas 中绘制条形堆栈? [英] How to plot bar stack in Pandas?
本文介绍了如何在 Pandas 中绘制条形堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是使用 Pandas 内置绘图模块绘制如下所示堆叠的条形
The objective is to plot a bar that stack as shown below using the Pandas builtin plot module
然而,我找不到任何试图实现类似目标的例子.
However, I cannot find any near example that tried to achieve similar objective.
我正在使用的示例代码如下:
The sample code that I am working is as below:
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt # noqa
matplotlib.use ('TkAgg')
data = {'name': ['Reg 1', 'Reg 1', 'Reg 1','Reg 2', 'Reg 2','Reg 2','Reg 2',
'Reg 3','Reg 3','Reg 3','Reg 3','Reg 3','Reg 4','Reg 4',],
'year': ['a', 'b', 'c','a','a','b','c',
'a','a','b','c','d','f','f'],
'reports': ['ay', 'by', 'cy','ay','ay','ay','cy',
'ay','ay','by','dy','dy','ry','rx']}
df = pd.DataFrame(data)
df_occ=df.apply(pd.Series.value_counts)
ax = df_occ.plot.bar(rot=0)
plt.show ()
感谢有人可以链接到我可能会错过的适当阅读材料.另外,我对可以实现上述目标的其他图书馆持开放态度.
Appreciate if someone can link to the appropriate reading material that I might miss. Also, I am open to other library that can achieve the aforementioned objective.
推荐答案
我们来试试:
fig, ax = plt.subplots(figsize=(10,6))
hatches = ['', '//']
bar_width = 0.45
names =set(df['name'])
for i, col in enumerate(['year','reports']):
width = bar_width if i==0 else - bar_width
s = pd.crosstab(df['name'], df[col])
s.plot.bar(width=width, align='edge', stacked=True, ax=ax, edgecolor='w', hatch=hatches[i])
for j, name in enumerate(names):
ax.text(j + width/2, 0, col, ha='center')
xmin,xmax = ax.get_xlim()
ax.set_xlim(xmin-0.4, xmax+0.5)
ax.legend(loc=[1.05, 0])
输出:
这篇关于如何在 Pandas 中绘制条形堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文