How to Change the "legend" Position in Matplotlib

In this tutorial, we will discuss how to change the legend position in Matplotlib.

First, we will discuss some basic concepts:

  • Matplotlib is a powerful visualization library written in Python for plots in 2D arrays. It was developed in the hands of John Hunter within the year 2002. Matplotlib could be a data visualization tool for multi-platform platforms based on NumPy arrays and is developed to integrate alongside the wider SciPy stack.
  • A legend is a space that describes the various elements that make up the graph. Within the matplotlib library, there is a function named legend() that can be utilized to create an axes-specific legend.
  • This attribute Loc in the legend() uses the attribute Loc to define the exact location in the legend.Default value for Loc will be loc = "best" (upper left). The strings that are best upper left, upper right, lower left, the lower left and right middle left middle, lower center, and center will place the legend in the appropriate area of the axes/figure.
Location StringLocation String
Best0
Upper right1
Upper left2
Lower left3
Lower right4
Right5
Centre left6
Centre right7
Lower centre8
Upper centre9
centre10

Approach

  • Step 1: We will import required modules and libraries.
  • Step 2: We will import or create the data.
  • Step 3: We will Plot a chart
  • Step 4: We will add legend
  • Step 5: We will set the position of legend by using loc.

Example 1:

Output:

How to Change the legend Position in Matplotlib

Example 2: With Position on Upper Right

Output:

How to Change the legend Position in Matplotlib

Example 3: Position of legend on Lower Left, with is also "3"

Output:

How to Change the legend Position in Matplotlib

Legend at lower left

Example 4: Legend Position at Center

Output:

How to Change the legend Position in Matplotlib

Conclusion

In this tutorial, we showed how to change the position of legend using Matplotlib in Python.






Latest Courses