簡體   English   中英

為箱線圖自定義 Seaborn 色調圖例

[英]Customize Seaborn Hue Legend for Boxplot

當我嘗試 plot 這個箱線圖時,年齡組的圖例如下所示。

%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

從 seaborn 0.10.1 開始,圖例 label 存儲在ax.legend_.texts[0]中,其中ax是由matplotlib返回的Axes返回的sns.boxplot() 這意味着您可以編輯圖例 label 而無需更改有關圖例的任何其他內容,如下所示。

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

根據您使用的 seaborn 版本,方法可能會有所不同。 請參閱2017 年2019 年的這些答案,以了解與舊版本略有不同的語法。

謝謝愛默生哈金 您的解決方案很有用。 我只是遍歷標簽列表來更新所有。 這是我更新的代碼和圖:

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

更新圖 更新圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM