Thursday, December 26, 2024
Google search engine
HomeLanguagesChange the legend position in Matplotlib

Change the legend position in Matplotlib

In this article, we will learn how to Change the legend position in Matplotlib. Let’s discuss some concepts :

  • Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002.
  • A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes.
  • The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings best upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, and center place the legend at the corresponding corner of the axes/figure.
Location String Location String
Best 0
Upper right 1
Upper left 2
Lower left 3
Lower right 4
Right 5
Center left 6
Center right 7
Lower center 8
Upper center 9
center 10

Approach:

  1. Import Library (Matplotlib)
  2. Import / create data.
  3. Plot a chart.
  4. Add legend.
  5. Set position of legend using loc.

Example 1:

Python3




# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend
plt.legend(['Legend'])
plt.show()


Output:

Without setting location of legend (best)

Example 2:

Python3




# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to upper left
plt.legend(['Legend'], loc='upper left')
plt.show()


Output:

Legend in Upper left

Example 3:

Python3




# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower left i.e; 4
plt.legend(['Legend'], loc=4)
plt.show()


Output:

Legend in Lower left

Example 4:

Python3




# importing packages
import numpy as np
import matplotlib.pyplot as plt
 
# create data
x = np.linspace(1, 50, 50)
np.random.seed(1)
y = np.random.randint(0, 20, 50)
 
# plot graph
plt.plot(x, y)
 
# add legend and set position to lower right
plt.legend(['Legend'], loc='lower right')
plt.show()


Output:

Legend in Lower right

RELATED ARTICLES

Most Popular

Recent Comments