简体   繁体   中英

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()

没有自定义图例的图

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.

图与 plt.legend

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.

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 Figure

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