2

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.

JohanC
  • 59,187
  • 8
  • 19
  • 45
Dumb ML
  • 327
  • 1
  • 10
  • Similar to [this post](https://stackoverflow.com/a/31754317/12046409), but leaving out the division by `total` – JohanC Jul 22 '20 at 17:23
  • To remove the spines: [How can I remove the top and right axis in matplotlib?](https://stackoverflow.com/questions/925024/how-can-i-remove-the-top-and-right-axis-in-matplotlib) – JohanC Jul 22 '20 at 17:26

1 Answers1

1

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

Scott Boston
  • 133,446
  • 13
  • 126
  • 161