Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add data Labels to seaborn countplot / factorplot

Tags:

python

seaborn

I use python3, seaborn countplot, my question :

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

enter image description here

Thanks a lot !

like image 588
vipqiaojin Avatar asked Dec 23 '22 09:12

vipqiaojin


2 Answers

I used a simple example data I generated but you can replace the df name and column name to your data:

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: enter image description here

You will be likely to play around with the location a little bit to make it look nicer.

like image 56
TYZ Avatar answered Jan 14 '23 18:01

TYZ


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

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: pic1

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: pic2

Check these links:

  1. https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar_label.html
  2. https://matplotlib.org/stable/api/container_api.html
like image 40
UniqueName Avatar answered Jan 14 '23 17:01

UniqueName