Jerry
Jerry

Reputation: 517

Python seaborn / matplotlib - show frequency in legend categories in sns.countplot()

I have plot generated using sns.countplot with a legend that uses the "hue" parameter. I would like to show the frequency of the "Category" count on the legend, along with the "Cross_Tab" label:

dfData:

Category    Cross_Tab
Apple       Yes
Apple       No
Peach       Yes
Peach       No
Dog         Yes
Dog         Yes

Plot:

fig = sns.countplot(x="Category", hue="Cross_Tab", data=dfData,  order=dfData.Category.value_counts().index)

Legend:

fig.legend(title="This is the Legend", loc='upper right')

This just shows the legend categories:

"This is the Legend"
Yes
No 

Desired output: The legend of the plot should look like this:

"This is the Legend"
Yes (n = 4)
No (n = 2)

After looking at various sources - I got as far as this, but it's not working:

x = dfData.Cross_Tab.value_counts()
fig.legend("n=(%s)"%(x, ), title="This is the Legend", loc='upper right') 

Upvotes: 0

Views: 909

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40667

You have to recreate each label individually.

Something like this seem to get the desired output:

plt.figure()
ax = sns.countplot(x="Category", hue="Cross_Tab", data=df,  order=df.Category.value_counts().index)

h, l = ax.get_legend_handles_labels()
counts = df.Cross_Tab.value_counts().reindex(l)
l = [f'{yn} (n={c})' for yn,c in counts.iteritems()]
ax.legend(h,l, title="This is the legend")

enter image description here

Upvotes: 2

Related Questions