显然,只有在渲染后才能读取图例的位置。坐标将以像素为单位。因此,可以使用创建一个新轴fig.add_axes
它将位于图例下方,使用图例的坐标和图形的尺寸。这是一个例子:
from matplotlib.pyplot import subplots
fig,ax = subplots()
fig.subplots_adjust(right=0.75)
ax.plot([0,1],'.-',label="line1")
ax.plot([0.1,1.1],'.-',label="line2")
leg = ax.legend(bbox_to_anchor=(1.05, 1),loc=2, borderaxespad=0)
fig.canvas.draw() # this draws the figure
# which allows reading final coordinates in pixels
leg_pxls = leg.get_window_extent()
ax_pxls = ax.get_window_extent()
fig_pxls = fig.get_window_extent()
# Converting back to figure normalized coordinates to create new axis:
pad = 0.025
ax2 = fig.add_axes([leg_pxls.x0/fig_pxls.width,
ax_pxls.y0/fig_pxls.height,
leg_pxls.width/fig_pxls.width,
(leg_pxls.y0-ax_pxls.y0)/fig_pxls.height-pad])
# eliminating all the tick marks:
ax2.tick_params(axis='both', left='off', top='off', right='off',
bottom='off', labelleft='off', labeltop='off',
labelright='off', labelbottom='off')
# adding some text:
ax2.text(0.1,0.1,"some text\nabout the\nlines")
生成这个数字:
如果不需要,可以轻松关闭框架。