class matplotlib.legend.Legend(parent, handles, labels
, *, loc
=None, numpoints=None, markerscale=None, markerfirst=True, reverse=False, scatterpoints=None, scatteryoffsets=None, prop=None, fontsize=None, labelcolor=None, borderpad=None, labelspacing=None, handlelength=None, handleheight=None, handletextpad=None, borderaxespad=None, columnspacing=None, ncols=1, mode=None, fancybox=None, shadow=None, title=None, title_fontsize=None, framealpha=None, edgecolor=None, facecolor=None, bbox_to_anchor
=None, bbox_transform
=None, frameon=None, handler_map=None, title_fontproperties=None, alignment=‘center’, ncol=1
, draggable=False)
1 函数调用方式
1.1.不传入参数:legend()
自动检测图例中显示的元素
import matplotlib.pyplot as plt
import numpy as np
plt.figure( figsize=(6, 4))
x = np.linspace(-3, 3, 100)
y1 = 2*x + 1
y2 = x**2
plt.plot(x, y2, color='blue', label='y=2x+1')
plt.plot(x, y1, color='red', linewidth=2.0, linestyle='--', label='y=x$^2$')
plt.xlim((-2, 2))
plt.ylim((-3, 3))
plt.legend()
1.2 传入一一对象的artist对象与标签:legend(handles, labels)
import matplotlib.pyplot as plt
import numpy as np
plt.figure( figsize=(6, 4))
x = np.linspace(-3, 3, 100)
y1 = 2*x + 1
y2 = x**2
y3 = np.power(x,3)
# 此处的line后面必须加,才能正常输出图例内容,否则显示空白图例框
line1, = plt.plot(x, y1, color='blue', ls=':')
line2, = plt.plot(x, y2, color='red', ls='--')
line3, = plt.plot(x, y3, color='green', ls='-')
plt.xlim((-2, 2))
plt.ylim((-3, 3))
plt.legend([line1,line2,line3],['y=x','$y=x^2$','$y=x^3$'],loc='lower right')
plt.show()
2 函数参数
2.1 参数: loc
loc: str or pair of floats, default: ‘best’ for Axes, ‘upper right’ for Figure
2.1.1 loc取值为str
Location String | Location Code | 位置 |
---|---|---|
‘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 | 中心 |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x = np.arange(5, 0, -1)
y1 = np.array([32, 31, 28, 22, 18])
fig,ax = plt.subplots(nrows=3,ncols=4,sharex=True,sharey=True, figsize=(12, 8))
plt.subplots_adjust(left=0.05,right=0.95,top=0.95,bottom=0.05, wspace=0,hspace=0)
ax[0,0].plot(x,y1,marker='o',lw=1,label='upper left', color='blue')
ax[0,0].legend(loc='upper left')
ax[0,1].plot(x,y1,marker='o',lw=1,label='upper right', color='blue')
ax[0,1].legend(loc='upper right')
ax[0,2].plot(x,y1,marker='o',lw=1,label='lower left', color='blue')
ax[0,2].legend(loc='lower left')
ax[0,3].plot(x,y1,marker='o',lw=1,label='lower right', color='blue')
ax[0,3].legend(loc='lower right')
ax[1,0].plot(x,y1,marker='o',lw=1,label='upper center', color='blue')
ax[1,0].legend(loc='upper center')
ax[1,1].plot(x,y1,marker='o',lw=1,label='lower center', color='blue'