pythonseabornlegendjointplotjointgrid

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


How to remove the legend in the seaborn.JoingGrid 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

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

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

    enter image description here

    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")  # 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)