How can I place the legend outside of a Seaborn plot? Can you provide some examples?

Placing the legend outside of a Seaborn plot allows for a better visualization of the data without obstructing any important information. This can be achieved by using the “bbox_to_anchor” argument in the “plt.legend()” function. By specifying the coordinates of where the legend should be placed, it can be positioned outside of the plot. Additionally, the “loc” argument can be used to specify the alignment of the legend. This method can be further customized by adjusting the font size and style of the legend. Some examples of this can be found in the official Seaborn documentation or by searching online for tutorials or guides.

Place Legend Outside a Seaborn Plot (With Examples)


You can use the bbox_to_anchor() argument to place a seaborn legend outside of the plot.

For example, you can use the following syntax to place the legend in the top right corner outside of the plot:

plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)

Note that the (1.05, 1) coordinates correspond to the (x, y) coordinates where the legend should be placed and the borderaxespad specifies the padding between the axes and the border legend.

The following examples show how to use this function in practice.

Example: Place Legend Outside of Seaborn Plot

The following code shows how to place the legend outside the top right corner of a seaborn plot:

import pandas as pd
import seaborn as sns
import matplotlib.pyplotas plt

#create fake data
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']})

#create scatterplot
sns.scatterplot(data=df, x='points', y='assists', hue='team')

#place legend outside top right corner of plot
plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)

And here’s how to place the legend outside the center right border of the plot:

#create scatterplot
sns.scatterplot(data=df, x='points', y='assists', hue='team')

#place legend outside center right border of plot
plt.legend(bbox_to_anchor=(1.02, 0.55), loc='upper left', borderaxespad=0)

Seaborn legend outside plot

And here’s how to place the legend outside the bottom right corner of the plot:

#create scatterplot
sns.scatterplot(data=df, x='points', y='assists', hue='team')

#place legend outside bottom right corner of plot
plt.legend(bbox_to_anchor=(1.02, 0.15), loc='upper left', borderaxespad=0)

Refer to the for a detailed explanation of the bbox_to_anchor() argument.

Refer to the for details on how to style the aesthetics of the plot.

Additional Resources

How to Change Legend Font Size in a Seaborn Plot

x