How to freely set the position, size and style of matplotlib legend (legend)

Problem Description

python matplotlib中:

plt.legend()

This line of code will help us display the legend, and usually, it will be placed in a nice location in the image. But if our data occupies the entire image, then there will be a problem with its placement.
Insert image description here

Parameters: position: loc

This parameter has some built-in positions. If these positions happen to be what you want, then just use this, it is very convenient.

Insert image description here

plt.legend(loc=1)#这个就等价于将图例放置在右上角的位置。

Parameters: Position: bbox_to_anchor

This is a great trick because it can control any position.

plt.legend(bbox_to_anchor=(1,0))

This thing is a coordinate, and the origin is the lower left corner of the picture. However, the numerical value of this coordinate represents a ratio. for example

(1,0)#右下角
(0,1)#左上角
(0.5,0.5)#中间
(0.4,0.4)#中间往左下一点,哈哈。

So, it's very simple, just slowly adjust it to the position you want. Note that the above also supports negative numbers.
Insert image description here

adjust size

We only need to pass the following thing into the legend function.

legend(prop = {
    
    'size':8})

In matplotlib, this prop variable can be used almost anywhere, not just legend.

Adjust style

The style we see is always vertical, every time. In fact, we can change it. For example, if we have two legends, then we set the following to 2, which means that they are displayed side by side by default instead of side by side.

legend(ncol=2)#默认为1,并列展示。

It becomes the following legend.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_39589455/article/details/129649318