【问题标题】:How to plot bar stack in Pandas?如何在 Pandas 中绘制条形堆栈?
【发布时间】:2020-12-30 03:07:54
【问题描述】:

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

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

我正在工作的示例代码如下:

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

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

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    我们试试吧:

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

    输出:

    【讨论】:

    • 嗨@quang,谢谢,这几乎是完美的。如果您可以在每个条形图上放置标签“年份”和“报告”,这是一个微不足道的要求。
    猜你喜欢
    • 2016-05-24
    • 2018-11-26
    • 2017-04-11
    • 1970-01-01
    • 2018-09-28
    • 2018-06-05
    相关资源
    最近更新 更多