1

I'm using MNIST data set and used sns.countplot() to plot the train images, which gave enter image description here

Is there a way to add the values of the bars somewhere? atop each one? inside/ below? Currently I'm seeing the actual values using print and that interferes with the sns.countplot() as the plots are always outputted before the prints

I'm using a very similar code to this but I still get no annotations.

# print and plot digit count
plt.figure(figsize=(12,5))
digit_count = sns.countplot(Y_train)
plt.title('Distribution of digits')

for d in digit_count.patches:
    digit_count.annotate('%{:.1f}'.format(d.get_height()), (d.get_x()+0.1, d.get_height()+50))

When printing the values from p.get_x(), and p.get_height() I get the right values, but they are not displayed atop the columns

Tried also adding a twinx... didn't help as well:

twin_table = digit_count.twinx()
twin_table.set_yticks(np.arange(0, 110, 10))

which only adds a secondary y axis (which I also don't know how to name...):

enter image description here

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

1 Answers1

0

library & dataset

import seaborn as sns, numpy as np
df = sns.load_dataset("iris")
 
# Basic countplot
ax = sns.countplot(x="species", y="sepal_length", data=df)

Calculate number of obs per group & median to position labels

medians = df.groupby(['species'])['sepal_length'].median().values
nobs = df['species'].value_counts().values
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs]

Add it to the plot

pos = range(len(nobs))
for tick,label in zip(pos,ax.get_xticklabels()):
   ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], horizontalalignment='center', size='x-small', color='w', weight='semibold')

sns.plt.show()

Community
  • 1
  • 1
Sherly
  • 75
  • 6