0
votes

I would like to add number of observations (nobs) to a horizontal box plot in seaborn - ideally above the whiskers and if not possible next to the median values. An alternative to either of these positions is OK also, but least preferable.

For this, I tried to adapt code from elsewhere (https://python-graph-gallery.com/38-show-number-of-observation-on-boxplot/) showing how to do this for vertical boxplots, but having trouble adapting this to horizontal boxplots.

This is my attempt so far:

df = sns.load_dataset("iris")

ax = sns.boxplot(y="species", x="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],nobs[tick],
         color='black', verticalalignment = "bottom")

sns.despine()

plt.show();

The result shows the number of observations (nobs) well outside the boxplot - see bottom left corner of the below picture.enter image description here

How do I move the (nobs) programmatically to within the figure as described at top of the question?

1
Did you consider replacing get_xticklabels with get_yticklabels? And maybe also change the order of pos[tick], medians[tick] to medians[tick],pos[tick]?JohanC
Yes, it works beautifully! Thank you Johan!veg2020

1 Answers

2
votes

box

Based on @JohanC comment, it works well. Please check the snippet

import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset("iris")
ax = sns.boxplot(y="species", x="sepal_length", data=df) 
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] 
pos = range(len(nobs))
for tick,label in zip(pos,ax.get_yticklabels()):
    ax.text(medians[tick],tick,nobs[tick],color='black', verticalalignment = "bottom")
sns.despine()
plt.show();