首页 > 解决方案 > 为 Boxplot 自定义 Seaborn Hue Legend

问题描述

当我试图绘制这个箱线图时,年龄组的图例如下所示。

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

没有自定义图例的图

但是当我尝试自定义图例时,我的代码是

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

f.legend(title="Age Group", labels=legend_label)行能够自定义标题和标签,但会导致标记错误。我需要将标记设置为上图中的颜色托盘。

图与 plt.legend

标签: pythonseaborn

解决方案


谢谢爱默生哈金。您的解决方案很有用。我只是遍历标签列表来更新所有。这是我更新的代码和图:

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

更新图 更新图


推荐阅读