Position Matplotlib Legends

We can easily position legends in Matplotlib using the loc parameter of the legend() method. The following values set position:

  • ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’
  • ‘upper center’, ‘lower center’, ‘center left’, ‘center right’
  • ‘center’

Here is what we have listed above:

  • The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ places the legend at the corresponding corner of the axes/figure.
  • The strings ‘upper center’, ‘lower center’, ‘center left’, ‘center right’ place the legend at the center of the corresponding edge of the axes/figure.
  • The string ‘center’ places the legend at the center of the axes/figure.

Before moving further, we’ve prepared a video tutorial to postion Matplotlib Legend:

Example

Let us now see an example of creating a graph in Matplotlib, set legends and its position as well:

import numpy as np
import matplotlib.pyplot as plt

# Data
a = np.arange(5)
b = [2,4,6,8,10]
c = [5, 6, 7, 8, 9]

# Create plots
fig = plt.figure()
ax = plt.subplot()
ax.plot(a, b, 'k--', label='Frequency')
ax.plot(a, c, 'k:', label='Periods')

# Create a legend using the Matplotlib Axes.legend() method in Python.
# Set the position using the loc parameter of the legend() method
ax.legend(loc='upper center')

# Plot Title
plt.title("Frequency of a Signal")

# Display
plt.show()

Output

Position Matplotlib Legends


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Add a Matplotlib Legend in a Graph
Change the background color of the Matplotlib legend
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment