Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move or remove the legend from a seaborn JointGrid or jointplot

How to remove the legend in the seaborn jointgrid plot?

The reference code is like below:

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried to use the following methods that are known to work on the other seaborn plots, but failed on the jointplot:

plt.legend([],[], frameon=False)
g._legend.remove()

>Solution :

  • To remove the legend, the correct part of the sns.JointGrid or sns.jointplot must be accessed.
    • In this case g.ax_joint is where the legend is located.
  • Tested in python 3.10, matplotlib 3.5.1, seaborn 0.11.2

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

enter image description here

  • Moving the JointGrid legend can be done with sns.move_legend, as shown in this answer.
    • This also requires using 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)

enter image description here


With sns.jointplot

penguins = sns.load_dataset("penguins")
g = sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")

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

# or 

# move the legend
# sns.move_legend(g.ax_joint, "lower right", title='Species', frameon=False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading