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.
- 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 2: With Position on Upper Right
Example 3: Position of legend on Lower Left, with is also "3"
Legend at lower left
Example 4: Legend Position at Center
In this tutorial, we showed how to change the position of legend using Matplotlib in Python.