1、不同自定义图例
# 导入对应的模块
from matplotlib import lines
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# 1、定义线图例
# 方法1
line1 = lines.Line2D([0], [0], label='line1', marker='o', lw=2, c='green')
# 方法2,注意别丢逗号
line2, = plt.plot([0], [0], label='line2', marker='X', lw=2, c='blue')
# 2、定义矩形图例
path1 = mpatches.Patch(color="red", label="patch")
# 3、定义散点图图例
s1 = plt.scatter([0], [0], label='scatter', marker='+')
# 4、显示图例
handles = [line1, path1, line2, s1]
fig, ax = plt.subplots(figsize=(6.4, 0.32)) # 根据行数更改0.32
# ax.legend(handles=handles, labels=["a","b","c","d"], mode="expand", ncol = 4, borderaxespad = 0) # mode='expand', 水平展示图例
ax.legend(handles=handles, mode="expand", ncol = 4, borderaxespad = 0)
ax.axis("off") # 去掉坐标刻度
plt.show()
2、plt.legend() 参数
- loc:图例位置,可取(‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center , right’, ‘lower center’, ‘upper center’, ‘center’) ;若是使用了bbox_to_anchor,则这项就无效了
- fontsize:int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},字体大小;
- frameon:是否显示图例边框,
- ncol:图例的列的数量,默认为1,
- title:为图例添加标题
- shadow:是否为图例边框添加阴影,
- markerfirst:True表示图例标签在句柄右侧,false反之,
- markerscale:图例标记为原图标记中的多少倍大小,
- numpoints:表示图例中的句柄上的标记点的个数,一般设为1,
- fancybox:是否将图例框的边角设为圆形
- framealpha:控制图例框的透明度
- borderpad:图例框内边距
- labelspacing:图例中条目之间的距离
- columnspacing=0.4: 调整图例中不同列之间的间距
- labels= Label_Com:设置图例中的名称
- scatterpoints=1:设置图例中对应图像只出现一次
- handletextpad=0.1:用此参数调节图例和标签之间的距离
- handlelength:图例句柄的长度
- bbox_to_anchor:(横向看右num1,纵向看下num2),‘num1’用于控制legend的左右移动,值越大,越向右边移动, ‘num2’用于控制legend的上下移动,值越大,越向上移动。如果要自定义图例位置或者将图例画在坐标外边,用它,比如bbox_to_anchor=(1.4,0.8),这个一般配合着ax.get_position(),set_position([box.x0, box.y0, box.width*0.8 , box.height])使用。用不到的参数可以直接去掉,有的参数没写进去,用得到的话加进去 , bbox_to_anchor=(1.11,0)。如果使用ax.legend的话,需在它之前加一句:
ax = plt.gca() #返回坐标轴
plt.legend(scatterpoints=1,labels = Label_Com, labelspacing=0.4,columnspacing=0.4,markerscale=2,bbox_to_anchor=(0.9, 0),ncol=12,prop=font1,handletextpad=0.1)
3、组图共享图例
即先创建一个ax = plt.gca(),在ax的基础上操作即可创建组图的共享图例。
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
labels = ['winter', 'spring', 'summer', 'autumn']
color = ['lightskyblue', 'lime', 'red', 'gold']
patches = [mpatches.Patch(color=color[i], label="{:s}".format(labels[i])) for i in range(len(color))]
ax = plt.gca()
# 下面一行中bbox_to_anchor指定了legend的位置
ax.legend(handles=patches, bbox_to_anchor=(0.95, 1.12), ncol=4) # 生成legend
plt.show()