Skip to content
Related Articles

Related Articles

Improve Article

How To Place Legend Outside the Plot with Seaborn in Python?

  • Last Updated : 16 Nov, 2020

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot made using matplotlib. Moreover, it also provides us different plotting techniques to ease our Exploratory Data Analysis(EDA). With these plots, it also becomes important to provide legends for a particular plot.

In this following article, we are going to see how can we place our Legend on our plot, and later in this article, we will also see how can we place the legend outside the plot using Seaborn

We will start by importing our necessary libraries. 

Python3




import seaborn as sns 
import matplotlib.pyplot as plt

We will be using Seaborn for not only plotting the data but also importing our dataset. Here we will be using the Gamma dataset by seaborn. 



Python3




# set our graph style to whitegrid
sns.set(style="whitegrid")
  
# load the gammas dataset
ds = sns.load_dataset("gammas")  
  
# use seaborn's lineplot to plot our timeplot
# and BOLD signal columns
sns.lineplot(data=ds, x="timepoint", y="BOLD signal", hue = "ROI"
  
plt.show()

Output:

We can see that this plots a beautiful line plot graph with the legends. We can see that the legend box is on the plot. This might be an issue in many plots, so we need to keep our legend box outside the plot. 

We can do this by using matplotlib’s legend function and providing its necessary parameters.

Python3




plt.legend(bbox_to_anchor=(1, 1), loc=2)

Output:



We can also tune our parameters according to our necessities. 

Python3




plt.legend(bbox_to_anchor=(1.02, 1), loc=2)

Output:

Hence, this technique can be used in many scenarios where the legend box comes on the graph which may be otherwise useful for our EDA. 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :