首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为Boxplot自定义Seaborn图例

为Boxplot自定义Seaborn图例
EN

Stack Overflow用户
提问于 2020-06-19 17:19:40
回答 2查看 3.4K关注 0票数 1

当我试图绘制这个方块图形时,年龄组的传说如下所示。

代码语言:javascript
复制
%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()

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

代码语言:javascript
复制
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)行能够自定义标题和标签,但它会导致标记中的错误。我需要将标记设置为彩色托盘,就像在前面的图中一样。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-19 17:37:50

从海运到0.10.1,图例标签存储在ax.legend_.texts[0]中,其中axsns.boxplot()返回的matplotlib Axes。这意味着您可以编辑图例标签,而无需按下面的方式更改有关图例的任何其他内容。

代码语言:javascript
复制
g = sns.boxplot(...)
new_legend_label = 'Age Group'
g.legend_.texts[0].set_text(new_legend_label)

根据所使用的海运版本的不同,方法可能有所不同。请参阅来自20172019的这些答案,以了解与旧版本略有不同的语法。

票数 1
EN

Stack Overflow用户

发布于 2020-06-19 17:57:50

谢谢你Emerson Harkin。你的解决方案很有用。我只是遍历标签列表来更新所有的标签。下面是我更新的代码和图:

代码语言:javascript
复制
%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()

最新数字

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62475459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档