Last Updated : 23 Jul, 2025
In this article, we will learn how to Change the legend position in Matplotlib. Let's discuss some concepts :
Approach:
Example 1:
Python
# 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:
Python
# 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 leftExample 3:
Python
# 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 leftExample 4:
Python
# 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 rightRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4