How to add a legend on Seaborn facetgrid bar plot using Matplotlib?


Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a dataframe with col1 columns.
  • Multi-plot grid for plotting conditional relationships.
  • Use map_dataframe(). This method is suitable for plotting with functions that accept a long-form DataFrame as a 'data' keyword argument and access the data in that DataFrame using string variable names.
  • Add a legend to the plot().
  • To display the figure, use show() method.

Example

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

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

df = pd.DataFrame({'col1': [3, 7, 8]})

g = sns.FacetGrid(df, col="col1", hue="col1")
g.map_dataframe(sns.scatterplot)
g.set_axis_labels("X", "Y")
g.add_legend()

plt.show()

Output

Updated on: 17-Jun-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements