Ahnaf
Ahnaf

Reputation: 53

Customize Seaborn Hue Legend for Boxplot

When I tried to plot this boxplot figure , legend of age group was shown as below.

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
plt.figure(figsize=(14,7))
sns.set(style="white", palette="Blues", color_codes=True)
f = sns.boxplot(x="RIAGENDRtxt", y="BPXSY1", hue="agegrp", data=df)

plt.savefig("out.png",pad_inches=0.5)
plt.show()

figure without customize legend

But when I tried to customize the legend my code is

plt.figure(figsize=(14,7))
sns.set(style="white", palette="Blues", color_codes=True)
f = sns.boxplot(x="RIAGENDRtxt", y="BPXSY1", hue="agegrp", data=df)

f.set_xlabel("Sex")
f.set_ylabel("Systolic Blood Pressure")

legend_label = ["(18, 30)", "(30, 40)", "(40, 50)", "(50, 60)", "(60, 70)", "(70, 80)"]
f.legend(title="Age Group", labels=legend_label)

plt.savefig("out.png",pad_inches=0.5)
plt.show()

This f.legend(title="Age Group", labels=legend_label) line was able to customize the title and labels but it caused errors in the markers. I need to set the markers to the color pallet as it was in the previous figure.

figure with plt.legend

Upvotes: 2

Views: 6342

Answers (2)

Ahnaf
Ahnaf

Reputation: 53

Thank You Emerson Harkin. Your solution was useful. I just iterate over list of labels to update all. Here is my updated code and figure:

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
plt.figure(figsize=(14,7))
sns.set(style="white", palette="Blues", color_codes=True)
f = sns.boxplot(x="RIAGENDRtxt", y="BPXSY1", hue="agegrp", data=df)

f.set_xlabel("Sex")
f.set_ylabel("Systolic Blood Pressure")

legend_label = ["(18, 30)", "(30, 40)", "(40, 50)", "(50, 60)", "(60, 70)", "(70, 80)"]
f.legend(title="Age Group")

n = 0
for i in legend_label:
    f.legend_.texts[n].set_text(i)
    n += 1

plt.show()

Updated Figue Updated Figure

Upvotes: 1

Emerson Harkin
Emerson Harkin

Reputation: 917

As of seaborn 0.10.1, the legend label is stored in ax.legend_.texts[0], where ax is the matplotlib Axes returned by sns.boxplot(). This means that you can edit the legend label without changing anything else about the legend as follows.

g = sns.boxplot(...)
new_legend_label = 'Age Group'
g.legend_.texts[0].set_text(new_legend_label)

Depending on what version of seaborn you're using, the method might be different. See these answers from 2017 and 2019 for slightly different syntax with older versions.

Upvotes: 1

Related Questions