1.目标
一个自定义legend的问题。参考:自定义legend。
2.参数
legend函数的参数如下。
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12), ncol=3)
loc表示图例的位置,有多种形式:
‘North’ # 图例标识放在图顶端
‘South’ # 图例标识放在图底端
‘East’ # 图例标识放在图右方
‘West’ # 图例标识放在图左方
‘NorthEast’ # 图例标识放在图右上方(默认)
‘NorthWest # 图例标识放在图左上方
‘SouthEast’ # 图例标识放在图右下角
‘SouthWest’ # 图例标识放在图左下角
或:
‘NorthOutside’ # 图例标识放在图框外侧上方
‘SouthOutside’ # 图例标识放在图框外侧下方
‘EastOutside’ # 图例标识放在图框外侧右方
‘WestOutside’ # 图例标识放在图框外侧左方
‘NorthEastOutside’ # 图例标识放在图框外侧右上方
‘NorthWestOutside’ # 图例标识放在图框外侧左上方
‘SouthEastOutside’ # 图例标识放在图框外侧右下方
‘SouthWestOutside’ # 图例标识放在图框外侧左下方
# (以上几个将图例标识放在框图外)
‘Best’ # 图标标识放在图框内不与图冲突的最佳位置
‘BestOutside’ # 图标标识放在图框外使用最小空间的最佳位置
bbox_to_anchor,表示legend的位置,前一个表示左右,后一个表示上下。当使用这个参数时,loc将不再起正常的作用。
ncol,ncol=3表示图例分三列显示。
3.缩放坐标轴
采用对坐标轴放大或是缩小的方式,但放大缩小的比率很难自动化控制到适合的位置,只能手动尝试调整,如下:
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width, box.height * 0.8])
首先按上面的方式,如果你想将图例放上面就box.height * 0.8,放右边就box.width * 0.8其它方式一样。
同时配合下面来使用。
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12), ncol=3)
主要是bbox_to_anchor参数的使用,自己可以修改参数尝试。
4.subplot问题
假设subplot(22x),那么可以分别调整不同子图的legend。比如保留第一个子图的legend,将其他子图的legend调整至图片无法正常显示的位置。如下:
if subplot_item == 0:
plt.legend(ncol=3, bbox_to_anchor=(2.0, 1.3)) # subplot1
elif subplot_item == 1:
plt.legend(bbox_to_anchor=(0, -20)) # subplot2
elif subplot_item == 2:
plt.legend(bbox_to_anchor=(0, 20)) # subplot3
else:
plt.legend(bbox_to_anchor=(0, 20)) # subplot4