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.
How do I move the (nobs) programmatically to within the figure as described at top of the question?
get_xticklabels
withget_yticklabels
? And maybe also change the order ofpos[tick], medians[tick]
tomedians[tick],pos[tick]
? – JohanC