【问题标题】:Customise Seaborn Hue Legend for Boxplot为 Boxplot 自定义 Seaborn Hue Legend
【发布时间】:2020-06-20 01:57:50
【问题描述】:

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

%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) 行可以自定义标题和标签,但会导致标记错误。我需要像上图中一样将标记设置为颜色托盘。

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    从 seaborn 0.10.1 开始,图例标签存储在 ax.legend_.texts[0],其中 axsns.boxplot() 返回的 matplotlib Axes。这意味着您可以编辑图例标签,而无需更改有关图例的任何其他内容,如下所示。

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

    根据您使用的 seaborn 版本,方法可能会有所不同。请参阅 20172019 的这些答案,了解与旧版本略有不同的语法。

    【讨论】:

      【解决方案2】:

      谢谢Emerson Harkin。您的解决方案很有用。我只是遍历标签列表以更新所有内容。这是我更新的代码和图:

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

      更新图

      【讨论】:

        猜你喜欢
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-13
        • 2020-04-08
        • 1970-01-01
        • 2021-10-29
        相关资源
        最近更新 更多