How to add counts and remove top and right spines of a countplot?

Viewed 115

How can I improve this graph by adding the count on the top of each bar and retrieving the lines on the top and on the right (just keeping the x and y axis)? In a "flexible" way (I mean, not just for this graph, but easily to replicate with another data)

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])
sns.countplot(df['target']);

I tried looking at some posts, like How to improve this seaborn countplot?, and even at the documentation (https://seaborn.pydata.org/generated/seaborn.countplot.html), but I couldn't find a these things.

1 Answers

IIUC, Try:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])
ax = sns.countplot(df['target']);
for p in ax.patches:
    height = p.get_height()
    ax.text(p.get_x()+p.get_width()/2.,
            height + 3,
            f'{p.get_height()}',
            ha="center") 
    
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

Output:

enter image description here

Related