【问题标题】:Stacked barplot for table表格的堆积条形图
【发布时间】:2021-07-03 06:08:03
【问题描述】:

我有一张表格,列出了不同的类别和一些相关的子类别。比如:

General Type Specific Food
fruit apple
fruit apple
meat ham
fruit banana
meat pork
vegetable lettuce

现在我想在堆叠的条形图中显示它,其中每个 常规类型 都有自己的条形图。这些条形中的每一个都应细分为其子类别(在本例中为 特定食物)。

最后会有三个酒吧(fruitmeat蔬菜)。其中 fruit 的高度为三,有两个不同的区域(apple 大小为 2, 大小为 1 >banana)等等,我想你明白了……或者你看看我上传的图片:

.

我希望有一个我只是没有找到的简单方法......

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    Seaborn 的countplot 可以进行计数并自动创建适当的图例。不幸的是,这要么将条形彼此相邻(默认dodge=True),要么将它们从y=0dodge=False)开始彼此重叠。一个想法是遍历生成的条形图并通过更改它们的 y 位置来堆叠它们。

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    data = [['fruit', 'apple'],
            ['fruit', 'apple'],
            ['meat', 'ham'],
            ['fruit', 'banana'],
            ['meat', 'pork'],
            ['vegetable', 'lettuce']]
    df = pd.DataFrame(data, columns=['General', 'Specific'])
    # df_grp = df.groupby(['General', 'Specific']).agg(len).reset_index().rename(columns={0:'Count'})
    
    ax = sns.countplot(data=df, x='General', hue='Specific', dodge=False)
    bottoms = {}
    for container in ax.containers:
        for bar in container:
            h = bar.get_height()
            if not np.isnan(h) and h > 0:
                x = bar.get_x()
                w = bar.get_width()
                if x in bottoms:
                    bar.set_y(bottoms[x])
                    bottoms[x] += h
                else:
                    bottoms[x] = h
                ax.text(x + w / 2, bottoms[x] - h / 2, f'{h:.0f}', ha='center', va='center')
    ax.relim()
    ax.autoscale() # recalculates the ylims due to the changed bars
    ax.yaxis.major.locator.set_params(integer=True)
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 如果此答案解决了您的问题,您可能会将marking 的答案视为已接受。
    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2014-02-09
    • 2020-09-14
    • 1970-01-01
    • 2021-01-17
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多