user308827
user308827

Reputation: 21971

Annotating seaborn lineplot legend with number of rows for each category

I want to get and show the number of rows of each type in a seaborn lineplot. E.g.

import seaborn as sns
fmri = sns.load_dataset("fmri")
ax = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri)

I want to show the number of rows with event 'stim' and number of rows with event 'cue' as an addition to the legend e.g. instead of showing 'stim' in the legend, it could show 'stim (23)' meaning that 23 rows have the event as 'stim'

Upvotes: 0

Views: 202

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40697

Something like this would do the trick:

fmri = sns.load_dataset("fmri")
x_col = 'timepoint'
y_col = 'signal'
hue_col = 'event'

ax = sns.lineplot(x=x_col, y=y_col, hue=hue_col, data=fmri)
handles,labels = ax.get_legend_handles_labels()
counts = fmri[hue_col].value_counts()
# labels[0] is used for the title by seaborn
new_labels = [labels[0]]+['{:s} ({:d})'.format(l, counts[l]) for l in labels[1:]]
ax.legend(handles, new_labels)

enter image description here

Upvotes: 1

Related Questions