<jupyter_start><jupyter_text>In the following example, we start from a simple boxplot and add annotations to it.  To do so we:  * calculate the median sepal_length for each group and store them in a variable named 'medians' * we then create a 'nobs' list which stores the number of observations for each group  * eventually, we add labels to our figure.  To add labels, keep in mind that seaborn is built on top of matplotlib, thus seaborn objects can be stored in matplotlib axes or figures (here we store the boxplot in a matplotlib.axes object named ax). This enables us to use matplotlib.axes .get_xticklabels() as well as .text() functions and its various parameters (horizontalalignment, size, color, weight) to add text to our figure.<jupyter_code># libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
df = sns.load_dataset('iris')
 
ax = sns.boxplot(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')
 
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10293159609120521, 'fraction_numerical': 0.001954397394136808, 'mean_word_length': 3.9548387096774196, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '401986', 'license': '0BSD', 'n_tokens_mistral': 483, 'n_tokens_neox': 466, 'n_words': 182, 'path': 'src/notebooks/38-show-number-of-observation-on-boxplot.ipynb', 'repo_name': 's-lasch/The-Python-Graph-Gallery', 'size': '1535'}