在使用matplotlib画图时,有时我们会需要添加图例来增强图像的可读性,具体使用方法如下:

import matplotlib.pyplot as plt
import numpy as np
import math
x1 = np.arange(0,5.1,0.01)
x1 = math.pi*x1
y1 = np.sin(x1)
y2 = np.cos(x1)
#在绘制图像时定义每条函数图像的label值,用于显示在图例上
p1 = plt.plot(x1,y1,label='sin(x)',color='b')
p2 = plt.plot(x1,y2,label='cos(x)',color='r')
plt.xlim(0,5)
#绘制图例,loc表示图例位置,1代表右上方
plt.legend(loc=1)
plt.show()

python图例顺序怎么改 python怎么添加图例_pyplot

图例中loc值对应的位置如下表所示:

对应位置

英文写法

对应数字

自适应

best

0

右上

upper right

1

左上

upper left

2

左下

lower left

3

右下

lower right

4

右侧

right

5

左侧居中

center left

6

右侧居中

center right

7

下侧居中

lower center

8

上侧居中

upper center

9

居中

center

10