如何在matplotlib中将文本框直接放在图例下方?

2024-10-01 00:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

使用matplotlib,我想在图例下方放置一个文本框,其中包含有关该图形的一些注释。我的传说在右边的轴心外。我的计划是找到图例在图形参照系中的位置,然后使用图形的text方法来放置注释。然而,我不知道如何得到这些图例坐标。如有任何建议或替代计划,将不胜感激。在


Tags: 方法text图形matplotlib建议计划文本框图例
1条回答
网友
1楼 · 发布于 2024-10-01 00:26:13

很显然,只有当它被渲染后,人们才能读懂它的位置。坐标将以像素为单位。因此,可以使用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")

这就产生了这个数字:

enter image description here

如果不需要,可以很容易地关闭框架。在

相关问题 更多 >