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

PythonServer Side ProgrammingProgramming

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

raja
Published on 08-Jul-2021 10:59:33
Advertisements