【问题标题】:How to add percentages on countplot in seaborn [duplicate]如何在seaborn的countplot上添加百分比[重复]
【发布时间】:2021-12-09 21:30:43
【问题描述】:

我有同样的问题with this post,并且已经尝试this solution(也是评论)。但我得到了奇怪的百分比结果。由于我还没有资格发表评论,所以我发布了这个问题。 就我而言,这是因为这条线的奇怪顺序而发生的,但我找不到解决方案。

a = [p.get_height() for p in plot.patches]

我的预期输出是每个Class 的总百分比将是 100%

这是我使用的第一个源代码

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

df = sns.load_dataset("titanic")

def with_hue(plot, feature, Number_of_categories, hue_categories):
    a = [p.get_height() for p in plot.patches]
    patch = [p for p in plot.patches]
    for i in range(Number_of_categories):
        total = feature.value_counts().values[i]
        # total = np.sum(a[::hue_categories])
        for j in range(hue_categories):
            percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
            x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
            y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height() 
            p3.annotate(percentage, (x, y), size = 11)
    plt.show()

plt.figure(figsize=(12,8))
p3 = sns.countplot(x="class", hue="who", data=df)
p3.set(xlabel='Class', ylabel='Count')

with_hue(p3, df['class'],3,3)

和第一个输出

在使用带有total = np.sum(a[::hue_categories]) 的总值时,给出这个输出

【问题讨论】:

    标签: python numpy seaborn bar-chart


    【解决方案1】:

    首先,请注意,在 matplotlib 和 seaborn 中,子图称为“斧头”。在研究文档和在线示例代码时,给这样的子图起一个诸如“p3”或“plot”之类的名称会导致不必要的混淆。

    seaborn 条形图中的条形图是有组织的,从属于第一个色调值的所有条形开始,然后是第二个,依此类推。因此,在给定的示例中,首先是蓝色,然后是橙色,最后所有的绿色条。这使得循环通过ax.patches 有点复杂。幸运的是,同样的补丁也可以通过ax.collections 获得,其中每个色调组形成一个单独的条形集合。

    下面是一些示例代码:

    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    
    def percentage_above_bar_relative_to_xgroup(ax):
        all_heights = [[p.get_height() for p in bars] for bars in ax.containers]
        for bars in ax.containers:
            for i, p in enumerate(bars):
                total = sum(xgroup[i] for xgroup in all_heights)
                percentage = f'{(100 * p.get_height() / total) :.1f}%'
                ax.annotate(percentage, (p.get_x() + p.get_width() / 2, p.get_height()), size=11, ha='center', va='bottom')
    
    df = sns.load_dataset("titanic")
    
    plt.figure(figsize=(12, 8))
    ax3 = sns.countplot(x="class", hue="who", data=df)
    ax3.set(xlabel='Class', ylabel='Count')
    
    percentage_above_bar_relative_to_xgroup(ax3)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2017-07-22
      • 1970-01-01
      相关资源
      最近更新 更多