Change the legend position in Matplotlib Read Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue Report 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 StringLocation StringBest0Upper right1Upper left2Lower left3Lower right4Right5Center left6Center right7Lower center8Upper center9center10 Approach: Import Library (Matplotlib)Import / create data.Plot a chart.Add legend.Set position of legend using loc. Example 1: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legendplt.legend(['Legend'])plt.show() Output: Without setting location of legend (best) Example 2: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to upper leftplt.legend(['Legend'], loc='upper left')plt.show() Output: Legend in Upper left Example 3: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower left i.e; 4plt.legend(['Legend'], loc=4)plt.show() Output: Legend in Lower left Example 4: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower rightplt.legend(['Legend'], loc='lower right')plt.show() Output: Legend in Lower right Last Updated : 26 May, 2021 Like Article Save Article Previous Matplotlib.axes.Axes.legend() in Python Next How to Change Legend Font Size in Matplotlib? Share your thoughts in the comments Add Your Comment Please Login to comment...