关于plt.legend()中bbox_to_anchor的理解
在⽤plt.legend()添加图例的时候,bbox_to_anchor()这个参数有时候是有两个元素,有时候是可以有四个元素,那么到底有什么区别?1. 两个元素borderbox
对于两个元素的bbox_to_anchor(),也就是(x,y),这个参数是代表了lengend_box的起点,并且是有后⾯的loc决定 的。
⾸先明确,lengend_box是⼀个四边形,在这⾥为了⽅便理解将它的四条边成为:
左边,右边,顶边,底边
例如,设置(0.5,0.5), loc='center',那么代表lengend_box的中⼼点(center)坐标是(0.5, 0.5)
设置(0.5,0.5), loc='lower center',那么代表底边的中点坐标是(0.5,0.5)
如图中标注的红点就是坐标(0.5,0.5)所在位置,然后根据loc参数的不同,对应到绿⾊的lengend_box位置也就不同。
2. 四个元素
对于四个元素的bbox_to_anchor(),也就是(x, y, width, height),情况就和上⾯两个元素的有所不同了。我们通过图来展⽰,会更清楚⼀点。
如图,红⾊框为bounding_box,绿⾊框为legend_box,在加上了(height, width)两个参数后,实际的中⼼(x=0.5, y=0.5)来到了红⾊框中,也就是图中⿊⾊点标记处,然后再根据(height, width)分别扩展。
那个(height, width)对于绿⾊框⼜产⽣了什么影响呢?我们从图中的紫⾊点标记处来看,绿⾊框的起点应该是和loc参数对应。
当loc='center'时,绿⾊框的起点应该是在红⾊框的正中⼼,然后根据(height,width)向四周边扩散(因为时center);
当loc='lower center'时,绿⾊框的起点在红⾊框的底边中⼼,然后根据(height,width)向两边以及上⾯扩散(因为是lower+center);
同理可以类推出其他的图。
附录——以上两个图的代码
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
locs =['upper right','lower left','center left','lower center','center', 'right']
x0, y0, width, height =0.5,0.5,0.1,0.4
x1, y1, width1, height1 =0.5,0.5,0,0
x = np.arange(0.1,4,0.1)
y =1.0/x
fig = plt.figure(figsize=(10,10))
idx =1
for i in range(0,2):
for j in range(0,3):
ax = fig.add_subplot(3,2, idx)
ax.plot(x, y, label=r'$\frac{1}{x}$')
ax.legend(loc=locs[idx-1], bbox_to_anchor=(x0, y0, width, height),
edgecolor='g', fontsize='large', framealpha=0.5,
borderaxespad=0)
ax.add_patch(
patches.Rectangle((x0, y0), width, height, color='r',
fill=False, ansAxes)
)
<(0.6,0.2, s="loc = '{}'".format(locs[idx-1]),
ansAxes)
idx +=1
fig1 = plt.figure(figsize=(10,10))
idx1 =1
for i in range(0,2):
for j in range(0,3):
ax1 = fig1.add_subplot(3,2, idx1)
ax1.plot(x, y, label=r'$\frac{1}{x}$')
ax1.legend(loc=locs[idx1-1], bbox_to_anchor=(x1, y1, width1, height1),            edgecolor='g', fontsize='large', framealpha=0.5,
borderaxespad=0)
ax1.add_patch(
patches.Rectangle((x1, y1), width1, height1, color='r',
fill=False, ansAxes)
)
<(0.6,0.2, s="loc = '{}'".format(locs[idx1-1]),
ansAxes)
idx1 +=1
plt.show()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。