matplotlib的使用——legend图例的设置

图例设置常用函数及其作用

plt.legend()

plt.legend(
	*args,
	**kwargs)

其中**kwargs包含常用的参数:
1、loc:图例位置,可取:‘best’、 ‘upper right’、‘upper left’、‘lower left’、‘lower right’、‘right’、‘center left’、‘center’、'right’、‘lower center’、‘upper center’、‘center’) 。
图片来自官网:

在这里插入图片描述

2、borderpad:图例的内边距 ,None或者float。
3、fontsize:int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},用于设置字体大小。
4、frameon: 是否显示图例边框,None或者bool。
5、fancybox:是否将图例框的边角设为圆形,None或者bool。
6、framealpha:控制图例框的透明度,None或者float。
7、ncol:图例列的数量,默认为1。
8、title:图例的标题
9、shadow: 是否为图例边框添加阴影,None或者bool。
10、markerfirst:bool量,True表示图例标签在句柄右侧,false反之。
11、markerscale: 图例标记为原图的多少倍。
12、labelspacing:图例中条目之间的距离,None或者float。
13、handlelength:图例中句柄的长度。
14、handles:填写用于添加到图例里的线条。
15、labels:对应着添加到图例里线条的标签。
应用示例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,1,50)
y1 = 2*x + 1
y2 = x**2

plt.figure(num=1,figsize=(8,5))
# 用于设置x轴的范围
plt.xlim((-1,1))
# 用于设置y轴的范围
plt.ylim((-2,5))
# 设置x轴的名称
plt.xlabel('I am x label')
# 设置y轴的名称
plt.ylabel('I am y label')
# 将新的x轴上的坐标设置为-1到1间隔数为10
newTicks = np.linspace(-1,1,10)
plt.xticks(newTicks)
# 将y轴坐标按照一定格式设置字符,-2对应really bad,-1对应little bad
plt.yticks([-2,-1.0,0,1.5,3], 
           ['really bad','little bad','normal','little good','pretty good'])
# 按照一定格式画线
line1, = plt.plot(x,y2,color = 'red',linewidth = 1.0,linestyle = '--',label = 'curve')
line2, = plt.plot(x,y1,label = 'straight line')
# 设置图例
plt.legend(loc = 'best', handles = [line1,line2,],labels = ['curve one','straight one'],
    shadow = True,
    fancybox = True,
    markerfirst = True,
    borderpad = 1.5,
    framealpha = 1,
    title = 'legend',
    labelspacing = 1.2)
plt.show() 

结果为:
在这里插入图片描述

天道酬勤 循序渐进 技压群雄
原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/15682357.html