简体   繁体   English

如何在seaborn的countplot上添加百分比

[英]How to add percentages on countplot in seaborn

I have same issue with this post , and already try this solution (also the comment).我对这篇文章有同样的问题,并且已经尝试了这个解决方案(也是评论)。 But i got weird percentage result.但我得到了奇怪的百分比结果。 Since I am not eligible yet to comment, I post this question.由于我还没有资格发表评论,所以我发布了这个问题。 As far as I tweak this, it's happen because of the weird order of this line but i can't find the solution.就我调整这一点而言,这是由于这一行的奇怪顺序而发生的,但我找不到解决方案。

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

My expected output is the total percentage of each Class will be 100%我的预期输出是每个Class的总百分比将是 100%

Here the first source code I use这是我使用的第一个源代码

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)

and the first output和第一个输出第一个输出

while using total value with total = np.sum(a[::hue_categories]) give this output使用 total 值 with total = np.sum(a[::hue_categories])给出这个输出第二个输出

First, note that in matplotlib and seaborn, a subplot is called an "ax".首先,请注意在 matplotlib 和 seaborn 中,子图被称为“ax”。 Giving such a subplot a name such as "p3" or "plot" leads to unnecessary confusion when studying the documentation and online example code.在研究文档和在线示例代码时,给这样的子图一个名称,例如“p3”或“plot”会导致不必要的混淆。

The bars in the seaborn bar plot are organized, starting with all the bars belonging to the first hue value, then the second, etc. So, in the given example, first come all the blue, then all the orange and finally all the green bars. seaborn 条形图中的条形是有序的,从属于第一个色调值的所有条形开始,然后是第二个等等。因此,在给定的示例中,首先是所有蓝色,然后是所有橙色,最后是所有绿色酒吧。 This makes looping through ax.patches somewhat complicated.这使得循环ax.patches变得有些复杂。 Luckily, the same patches are also available via ax.collections , where each hue group forms a separate collection of bars.幸运的是,同样的补丁也可以通过ax.collections ,其中每个色调组形成一个单独的条形集合。

Here is some example code:下面是一些示例代码:

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

每 x 组的百分比条形图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM