如何从seaborn JointGrid或jointplot中移动或删除图例

Hyu*_*Kim 5 python legend seaborn jointplot jointgrid

如何去掉剧情中的图例seaborn.JoingGrid

参考代码如下:

import matplotlib.pyplot as plt
import seaborn as sns

penguins = sns.load_dataset("penguins")

g = sns.JointGrid(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")
g.plot_joint(sns.scatterplot)
sns.boxplot(data=penguins, x=g.hue, y=g.y, ax=g.ax_marg_y)
sns.boxplot(data=penguins, y=g.hue, x=g.x, ax=g.ax_marg_x)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我尝试使用以下已知适用于其他seaborn地块的方法,但在jointplot上失败了:

plt.legend([],[], frameon=False)
g._legend.remove()
Run Code Online (Sandbox Code Playgroud)

Tre*_*ney 3

  • sns.JointGrid要删除图例,必须访问 正确的部分。
    • 在本例中g.ax_joint就是图例所在的位置。
  • 正如mwaskom的评论中所述,Matplotlib 轴具有.legend(创建图例的方法)和.legend_(结果对象)。不要访问以下划线 (_legend) 开头的变量,因为这表明它们是私有的。
  • 测试于python 3.10, matplotlib 3.5.1,seaborn 0.11.2
    • g.plot_joint(sns.scatterplot, legend=False)可以用它来代替。

sns.JointGrid

import seaborn as sns

penguins = sns.load_dataset("penguins")

g = sns.JointGrid(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")
g.plot_joint(sns.scatterplot)  # legend=False can be added instead
sns.boxplot(data=penguins, x=g.hue, y=g.y, ax=g.ax_marg_y)
sns.boxplot(data=penguins, y=g.hue, x=g.x, ax=g.ax_marg_x)

# remove the legend from ax_joint
g.ax_joint.legend_.remove()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 可以通过移动JointGrid图例来完成sns.move_legend,如本答案所示。
    • 这也需要使用g.ax_joint.
penguins = sns.load_dataset("penguins")

g = sns.JointGrid(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")
g.plot_joint(sns.scatterplot)
sns.boxplot(data=penguins, x=g.hue, y=g.y, ax=g.ax_marg_y)
sns.boxplot(data=penguins, y=g.hue, x=g.x, ax=g.ax_marg_x)

# move the legend in ax_joint
sns.move_legend(g.ax_joint, "lower right", title='Species', frameon=False)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


sns.jointplot

  • g.ax_joint.legend_.remove()可以使用,但通过传递legend=False到图可以更轻松地删除图例:sns.jointplot(..., legend=False)
  • g.ax_joint.仍然需要移动图例。
penguins = sns.load_dataset("penguins")
g = sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")  # legend=False can be added instead

# remove the legend
g.ax_joint.legend_.remove()

# or 

# move the legend
# sns.move_legend(g.ax_joint, "lower right", title='Species', frameon=False)
Run Code Online (Sandbox Code Playgroud)