简体   繁体   中英

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. Eg

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 eg instead of showing 'stim' in the legend, it could show 'stim (23)' meaning that 23 rows have the event as 'stim'

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM