python - 为 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)
行能够自定义标题和标签,但会导致标记错误。我需要将标记设置为上图中的颜色托盘。
解决方案
谢谢爱默生哈金。您的解决方案很有用。我只是遍历标签列表来更新所有。这是我更新的代码和图:
%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()
更新图
推荐阅读
- azure - 计时器触发的 Azure 功能中的 Azure 服务总线客户端
- jquery - Google reCaptchav2 错误所需参数:站点密钥
- javascript - Angular 将 HTML 响应数据显示到视图中
- python - Python Django 以相同的形式更新用户和用户配置文件
- actions-on-google - 从 Google Home 应用中移除“Google Actions”项目
- python - 基于峰值对图像进行切片
- android - 点击 AdMOb 横幅时如何避免破坏应用程序?
- python - 计算另一个表中每个对象的使用次数
- php - laravel 的返回是否默认返回 json?
- python - 使用 File 中的 python matplotlib 绘制时间和浮点值