Move Seaborn Plot Legend to a Different Position

Move seaborn plot legend to a different position

Building on @user308827's answer: you can use legend=False in factorplot and specify the legend through matplotlib:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")
  • plt acts on the current axes. To get axes from a FacetGrid use fig.
    • g.fig.get_axes()[0].legend(loc='lower left')

How to move legend to outside of a seaborn scatterplot?

Please try the following:

g.legend(loc='center left', bbox_to_anchor=(1.25, 0.5), ncol=1)

You can change the first number to negative to put your legend on the left side if you want.

If you're using Jupyter IDE, you need to put both lines of your code in the same cell and run them together to get the output. In addition, there is no such thing as sns object. Most of the functions in seaborn return a matplotlib Axes object where you can use all the methods associated with the Axes object, like the one (i.e., .legend()) you are using here.

Moving the Legend in a Seaborn Graph in Python

Seaborn is not good at handling legends, if you have this issue, turn off the legend in seaborn (legend = False) and try to override it through matplotlib.

g = sns.lmplot('credibility', 'percentWatched', data=data, legend = False, hue = 'gender', markers = [".", "."], x_jitter = True, y_jitter = True, size=5, palette="Set2", scatter_kws={'alpha': 0.2})
g.set(xlabel = 'Credibility Ranking\n ← Low High →', ylabel = 'Percent of Video Watched [%]')
g.set(xlim=(1, 7))

# replace labels
new_labels = ['Male', 'Female']
plt.legend(bbox_to_anchor=(1.05, 0.5), title='Gender', labels = new_labels)

Hope it will help.

Edit labels and move legend in seaborn

In the current version of Seaborn's scatterplot (0.11.1), you can first create the legend in full and afterwards change it by calling ax.legend() again.

Note that the return value of sns.scatterplot is an ax as it is an axes-level function. This should not be confused with figure level functions which return a complete grid of "axes" and often are written as g = sns....

Different seaborn functions create legends in different ways. Depending on the options used, the legend can become quite intricate and not easy to change. Making legends easier to modify is planned in Seaborn's future developments.

from matplotlib import pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips, legend='full')
ax.legend(title='Smoker', bbox_to_anchor=(1.05, 1), labels=['Hell Yeh', 'Nah Bruh'])
plt.tight_layout()
plt.show()

resulting plot

How to change legend position in seaborn kdeplot?

Update Seaborn 0.11.2 added a new function sns.move_legend() that leaves the legend intact after moving. Apart from moving the legend, also other parameters can be changed, such as the number of columns (ncol=...) or the title (title=...).

sns.move_legend(ax, bbox_to_anchor=(0.05, 0.95), loc='upper left')

Old answer (for versions before 0.11.2)

The current seaborn (0.11.0) and matplotlib (3.3.2) versions give an error No handles with labels found to put in legend.

But the following approach seems to work. Note that _set_loc(2) only accepts a code, not a string, where 2 corresponds to 'upper left'.

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({"c": np.random.randn(10000).cumsum(),
"scan": np.repeat([*'abcd'], 2500)})
ax = sns.kdeplot(data=df, x="c", hue="scan", shade=True, palette="deep")
ax.legend_.set_bbox_to_anchor((0.05, 0.95))
ax.legend_._set_loc(2)
plt.show()

example plot

PS: Explicitly providing the legend labels also seems to work, but then probably hue_order is needed to ensure the order is the same.

scan_labels = np.unique(df['scan'])
ax = sns.kdeplot(data=df, x="c", hue="scan", hue_order=scan_labels, shade=True, palette="deep", legend=True)
ax.legend(labels=scan_labels, bbox_to_anchor=(0.05, 0.95), loc='upper left', title='scan')

Seaborn Pariplot: how to move legend and set style

pairplot already adds a legend outside the plot matrix. I do not know how you could get it inside of plot area. Probably there is something with plot figure size. I need more information about your code to detect the issue.

I've used test data in order to show some examples of plot legend locations.

# pip install matplotlib
# pip install seaborn

import seaborn as sns
import matplotlib.pyplot as plt

penguins = sns.load_dataset("penguins")

g = sns.pairplot(penguins, hue="species")

handles = g._legend_data.values()
labels = g._legend_data.keys()
g.fig.legend(handles=handles, labels=labels, loc='upper center', ncol=1)
g.fig.legend(handles=handles, labels=labels, loc='lower center', ncol=3)
g.fig.legend(handles=handles, labels=labels, loc='upper left', ncol=3)
g.fig.subplots_adjust(top=0.92, bottom=0.08)

plt.show()

enter image description here



Related Topics



Leave a reply



Submit