A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/change-the-legend-position-in-matplotlib/ below:

Change the legend position in Matplotlib

Change the legend position in Matplotlib

Last Updated : 23 Jul, 2025

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:

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 left

Example 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 left

Example 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 right

RetroSearch 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