gpt4 book ai didi

python - 如何在 Pandas 中绘制条形堆栈?

转载 作者:行者123 更新时间:2023-12-04 01:14:17 25 4
gpt4 key购买 nike

目标是使用 Pandas 内置绘图模块绘制如下所示堆叠的条形图

Expected Output

但是,我找不到任何试图实现类似目标的例子。

我正在使用的示例代码如下:

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 ()

如果有人可以链接到我可能错过的适当阅读 Material ,我将不胜感激。此外,我对可以实现上述目标的其他图书馆持开放态度。

最佳答案

让我们试试:

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])

输出:

enter image description here

关于python - 如何在 Pandas 中绘制条形堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63849660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com