How to add legend in Seaborn

You can add a legend in Seaborn with the following code. In this article, you’ll see two examples with solutions. These examples help you to understand how to add legends to the Seaborn plot. I highly recommend you “Python Crash Course Book” to learn Python.

Example 1: Add legend in Seaborn lineplot

# Import the required libraries
import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd

# Create Data
a = pd.DataFrame({"Temp 1": [25, 35, 33, 34, 41, 36],
                  "Temp 2" : [39, 33, 32, 35, 37, 31]})

# Draw the Lineplot
sns.lineplot(data=a)

# Add legend and title of legend
plt.legend(labels=["Temperature 1","Temperature 2"], title = "Weather")

Output:

Add legend and title of legend

Example 2: Add legend outside the plot

# Import the required libraries
import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd

# Create Data
a = pd.DataFrame({"Temp 1": [25, 35, 33, 34, 41, 36],
                  "Temp 2" : [39, 33, 32, 35, 37, 31]})

# Draw the Lineplot
sns.lineplot(data=a)

# Add legend outside the plot
plt.legend(labels=["Temperature 1","Temperature 2"], loc = 2, bbox_to_anchor = (1,1))

Output:

Add legend outside the plot

Leave a Comment

Your email address will not be published.