How to move the legend to outside of a Seaborn scatterplot in Matplotlib?


To move the legend to outside of a Seaborn scatterplot, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Make a Pandas dataframe with three coulmns, column1, column2 and column3.
  • Draw a scatterplot with possibility of several semantic groupings.
  • To place the legend outside the plot, use bbox_to_anchor in legend() method.
  • To display the figure, use show() method.

Example

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(dict(col1=[2, 1, 4],
                       col2=[5, 2, 1],
                       col3=[4, 0, 1]))

sns.scatterplot(data=df)

plt.legend(bbox_to_anchor=(1.25, 1), borderaxespad=0)

plt.show()

Output

Updated on: 08-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements