如何在matplotlib中的图例正下方放置一个文本框? [英] How to place a text box directly below legend in matplotlib?

查看:79
本文介绍了如何在matplotlib中的图例正下方放置一个文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using matplotlib, I'd like to place a text box below the legend, containing some notes about the figure. My legend is outside the axes to the right. My plan was to find the legend's position in the figure's frame of reference, then use the text method of the figure to place my notes. However, I can't figure out how to get those legend coordinates. Any suggestions or alternative plans would be much appreciated.

推荐答案

显然只有在渲染后才能读取图例的位置.坐标将以像素为单位.因此,可以使用 fig.add_axes 创建一个新轴,该轴将使用图例坐标和图形尺寸正好位于图例下方.这是一个示例:

Apparently one can only read the legend's position once its rendered. The coordinates will be in pixels. So, it is possible to create a new axis using fig.add_axes that will be just below the legend using the legend's coordinates and the figure's dimensions. Here is an example:

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")

生成这个数字:

如果不需要,可以轻松关闭框架.

The frame can be turn off easily if not needed.

这篇关于如何在matplotlib中的图例正下方放置一个文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆