How to Change the “legend” Position in Matplotlib

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 String Location String
Best 0
Upper right 1
Upper left 2
Lower left 3
Lower right 4
Right 5
Centre left 6
Centre right 7
Lower centre 8
Upper centre 9
centre 10

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.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263285.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论