Open In App

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 :

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:




# 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:




# 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:




# 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:




# 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


Article Tags :