简体   繁体   English

如何将数据标签添加到seaborn countplot / factorplot

[英]how to add data Labels to seaborn countplot / factorplot

I use python3, seaborn countplot, my question :我使用 python3,seaborn countplot,我的问题:

  1. how to add the count values for every bar?如何为每个条添加计数值? Show the label at the top of each bar?在每个栏的顶部显示标签?
  2. how to have these bars in descending order?如何按降序排列这些条?

I wrote this:我是这样写的:

fig = plt.figure(figsize=(10,6))
sns.countplot(data_new['district'],data=data_new)
plt.show()

在此处输入图片说明

Thanks a lot !非常感谢 !

I used a simple example data I generated but you can replace the df name and column name to your data:我使用了我生成的一个简单示例数据,但您可以将 df 名称和列名称替换为您的数据:

ax = sns.countplot(df["coltype"], 
                   order = df["coltype"].value_counts().index)

for p, label in zip(ax.patches, df["coltype"].value_counts().index):
    ax.annotate(label, (p.get_x()+0.375, p.get_height()+0.15))

This generates:这会产生: 在此处输入图片说明

You will be likely to play around with the location a little bit to make it look nicer.您可能会稍微调整一下该位置以使其看起来更好。

I know it's an old question, but I guess there is a bit easier way of how to label a seaborn.countplot or matplotlib.pyplot.bar than in previous answer here (tested with matplotlib-3.4.2 and seaborn-0.11.1).我知道这是一个老问题,但我想如何标记seaborn.countplotmatplotlib.pyplot.bar比之前的答案更简单一些(使用 matplotlib-3.4.2 和 seaborn-0.11.1 测试) .

With absolute values:使用绝对值:

ax = sns.countplot(x=df['feature_name'],
                   order=df['feature_name'].value_counts(ascending=False).index);

abs_values = df['feature_name'].value_counts(ascending=False).values

ax.bar_label(container=ax.containers[0], labels=abs_values)

Example:例子: 图片1

With absolute & relative values:绝对值和相对值:

ax = sns.countplot(x=df['feature_name'],
                   order=df['feature_name'].value_counts(ascending=False).index);
        
abs_values = df['feature_name'].value_counts(ascending=False)
rel_values = df['feature_name'].value_counts(ascending=False, normalize=True).values * 100
lbls = [f'{p[0]} ({p[1]:.0f}%)' for p in zip(abs_values, rel_values)]

ax.bar_label(container=ax.containers[0], labels=lbls)

Example:例子: 图片2

Check these links:检查这些链接:

  1. https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html
  2. https://matplotlib.org/stable/api/container_api.html https://matplotlib.org/stable/api/container_api.html

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

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