【问题标题】:Stacked bar chart in SeabornSeaborn 中的堆积条形图
【发布时间】:2020-03-21 04:00:01
【问题描述】:

我有以下数据:

countries2012 = [
    'Bolivia',
    'Brazil',
    'Sri Lanka',
    'Dominican Republic',
    'Indonesia',
    'Kenya',
    'Honduras',
    'Mozambique',
    'Peru',
    'Philipines',
    'India',
    'Vietnam',
    'Thailand',
    'USA',
    'World'
]

percentage2012 = [ 
    0.042780099,
    0.16599952,
    0.012373058,
    0.019171717,
    0.011868674,
    0.019239173,
    0.00000332,
    0.014455196,
    0.016006654,
    0.132970981,
    0.077940824,
    0.411752517,
    0.017986798,
    0.017361808,
    0.058076027
]

countries2013 = [
    'Bolivia',
    'Brazil',
    'Sri Lanka',
    'Dominican Republic', 
    'Indonesia', 
    'Honduras',
    'Mozambique', 
    'Peru', 
    'Philippines', 
    'India', 
    'Vietnam', 
    'Thailand', 
    'USA',
    'World'  
]

percentage2013 = [
    0.02736294,
    0.117160272, 
    0.015815952 ,
    0.018831589,
    0.020409103 ,
    0.00000000285,
    0.018876854,
    0.018998639,
    0.117221146,
    0.067991687,
    0.496110972,
    0.019309486,
    0.026880553,
    0.03503080414999993
]

我想制作一个堆积条形图,以便在 2012 年和 2013 年有一个堆积条形图。

由于 2012 年和 2013 年的国家不同,我该怎么办?

【问题讨论】:

    标签: matplotlib seaborn


    【解决方案1】:

    由于这个问题要求 Seaborn 中的堆积条形图,并且接受的答案使用 pandas,我想我会提供一种实际使用 Seaborn 的替代方法。

    Seaborn 给出了 stacked bar 的示例,但它有点 hacky,绘制总数,然后在其上叠加条形图。相反,您实际上可以使用直方图和weights 参数。

    import pandas as pd
    import seaborn as sns
    
    # Put data in long format in a dataframe.
    df = pd.DataFrame({
        'country': countries2012 + countries2013,
        'year': ['2012'] * len(countries2012) + ['2013'] * len(countries2013),
        'percentage': percentage2012 + percentage2013
    })
    
    # One liner to create a stacked bar chart.
    ax = sns.histplot(df, x='year', hue='country', weights='percentage',
                 multiple='stack', palette='tab20c', shrink=0.8)
    ax.set_ylabel('percentage')
    # Fix the legend so it's not on top of the bars.
    legend = ax.get_legend()
    legend.set_bbox_to_anchor((1, 1))
    

    【讨论】:

    • 我已经更新了我的 seaborn,但没有任何改变。它仍然抛出 AttributeError: module 'seaborn' has no attribute 'histplot'。我的 seaborn 版本是“0.10.1”。我该如何解决?
    • @TonyBrand 我相信你需要升级到 0.11。您可以在此处查看 histplot 上的文档:seaborn.pydata.org/generated/seaborn.histplot.html。在旧版本中可能可以使用另一种方法,但我不确定。
    【解决方案2】:

    IIUC,您可以创建一个Pandas 数据框并使用它的绘图功能:

    import pandas as pd
    df = pd.concat([pd.DataFrame({2012:percentage2012}, index=countries2012),
                    pd.DataFrame({2013:percentage2013}, index=countries2013)],
                   axis=1, sort=False)
    
    df.T.plot.bar(stacked=True, figsize=(12,6))
    

    输出:

    【讨论】:

    • 有没有一种简单的方法可以让堆栈以相反的顺序排列(使国家从上到下以相同的顺序排列,无论是在图例中还是在堆栈中)?
    • df.T.iloc[::-1].plot...?
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2020-01-30
    • 2018-12-17
    • 2021-06-18
    • 2021-07-10
    • 2017-10-14
    • 2017-02-26
    相关资源
    最近更新 更多