In this tutorial, we will look at how to change the legend position inside a matplotlib plot with the help of some examples.
You can use the loc
keyword parameter in the matplotlib.pyplot.legend()
function to specify the location of the legend in a matplotlib plot.
There are different location values that you can pass to the loc
parameter –
- You can use the strings ‘upper left’, ‘upper right’, ‘lower left’, and ‘lower right’ to place the legend at the corresponding corners.
- Use the strings ‘upper center’, ‘lower center’, ‘center left’, and ‘center right’ to place the legend at the center of the corresponding axes/figure edge.
- Use the string ‘center’ to place the legend at the center of the axes/figure.
- The string ‘best’ places the legend at a location (one among the above nine mentioned) that minimizes the overlap with the other content.
The default value for the loc
parameter is ‘best’.
Let’s now look at some examples of using the above syntax –
First, we will create a matplotlib plot with the default legend.
import matplotlib.pyplot as plt # x values - years x = [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] # y1 values - goals by Lionel Messi in club football y1 = [73, 60, 41, 58, 41, 54, 45, 51, 31, 38] # y2 values - goals by Cristiano Ronaldo in club football y2 = [60, 55, 51, 61, 51, 42, 44, 28, 37, 36] # plot y1 on a line plot plt.plot(x, y1) # plot y2 on a line plot plt.plot(x, y2) # add axes labels plt.xlabel('Year') plt.ylabel('Goals in Club Football') # add plot title plt.title("Messi vs Ronaldo") # add plot legend plt.legend(['Messi', 'Ronaldo'])
Output:
Here, we plot the goals scored by Lionel Messi and Cristiano Ronaldo in club football from 2011 to 2022. Note that the year 2011 means the club football season starting in 2011 (that is, the 2011-2012 season).
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
The legend is placed at the top right in this example, which matplotlib determined to be the ‘best’ location for the legend.
Example 1 – Place legend at bottom left
Let’s replot the above plot but with the legend at the bottom left this time. For this, we need to pass ‘lower left’ to the loc
parameter.
# plot x and y on a line plot plt.plot(x, y1) plt.plot(x, y2) # add axes labels plt.xlabel('Year') plt.ylabel('Goals in Club Football') # add plot title plt.title("Messi vs Ronaldo") # add plot legend plt.legend(['Messi', 'Ronaldo'], loc='lower left')
Output:
The legend is now positioned at the lower left corner of the plot.
Example 2 – Place legend at upper center
You can similarly place the legend at other positions in the chart. For example, let’s now place the legend at the upper center. For this, pass ‘upper center’ to the loc
parameter.
# plot x and y on a line plot plt.plot(x, y1) plt.plot(x, y2) # add axes labels plt.xlabel('Year') plt.ylabel('Goals in Club Football') # add plot title plt.title("Messi vs Ronaldo") # add plot legend plt.legend(['Messi', 'Ronaldo'], loc='upper center')
Output:
The legend is now placed at the upper center position.
Example 3 – Change legend position in subplots
To change the position of a legend in a subplot, you’ll have to use the subplot’s axes object’s legend()
function which is very similar to the matplotlib.pyplot.legend()
function which works for a single plot (or the latest plot in subplots).
First, let’s create a plot with two subplots.
# create subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5)) # plot the first subplot ax1.plot(x, y1) ax1.plot(x, y2) # add axis labels ax1.set_xlabel('Year') ax1.set_ylabel('Goals in Club Football') # add legend ax1.legend(['Messi', 'Ronaldo']) # plot the second subplot ax2.plot(x, y1) ax2.plot(x, y2) # add axis labels ax2.set_xlabel('Year') ax2.set_ylabel('Goals in Club Football') # add legend ax2.legend(['Messi', 'Ronaldo'])
Output:
Here, we created two subplots. Both the subplots have the same data but that is not important. You can see that legend is placed at the best location inside each of those plots.
Let’s now change the position of the legend in the first subplot to ‘lower left’ and the legend in the second subplot to ‘center right’.
# create subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5)) # plot the first subplot ax1.plot(x, y1) ax1.plot(x, y2) # add axis labels ax1.set_xlabel('Year') ax1.set_ylabel('Goals in Club Football') # add legend ax1.legend(['Messi', 'Ronaldo'], loc='lower left') # plot the second subplot ax2.plot(x, y1) ax2.plot(x, y2) # add axis labels ax2.set_xlabel('Year') ax2.set_ylabel('Goals in Club Football') # add legend ax2.legend(['Messi', 'Ronaldo'], loc='center right')
Output:
You might also be interested in –
- Matplotlib – Change Line to Dots
- Matplotlib – Add an Average Line to the Plot
- How to make text italic in a Matplotlib plot?
- How to bold text in a Matplotlib plot?
- Matplotlib – Remove the frame without altering the ticks and the tick labels
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.