文本框自动定位
我想用类似于图例中'loc'选项的关键字参数来定位一个文本框,比如'upper left'(左上角)、'upper right'(右上角)、'lower right'(右下角)、'lower left'(左下角)。这样做的主要目的是让文本框和图例对齐。我在这里找到了一些建议:在matplotlib中自动定位文本框,但它仍然需要我调整坐标才能达到我想要的效果,特别是当我想把文本框放在图表区域的右侧时,这还得根据文本框内文本的长度来决定。除非我能把文本框的一个右角作为坐标的参考点。
2 个回答
1
如果想要设置文本相对于图例的位置,首先要知道图例的位置。诀窍是,你得先把图例画出来,然后获取它的 边界框(bbox)。下面是一个例子:
import matplotlib.pyplot as plt
from numpy import random
# Plot some stuff
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(random.rand(10))
# Add a legend
leg = ax.legend('line', loc = 'upper right')
# Draw the figure so you can find the positon of the legend.
plt.draw()
# Get the Bbox
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes)
# Add text relative to the location of the legend.
ax.text(bb.x0, bb.y0 - bb.height, 'text', transform=ax.transAxes)
plt.show()
另一方面,如果你只需要定义文本从右边的位置,你可以像这样设置文本的水平对齐方式为右对齐 。
plt.text(x, y, 'text', ha = 'right')
3
你可以使用matplotlib中的AnchoredText来实现这个功能。具体的做法可以参考这里:
简单来说:
from matplotlib.offsetbox import AnchoredText
anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)
每个loc数字对应图表中的一个位置,比如loc=2表示“左上角”。完整的位置列表可以在这里找到:http://matplotlib.org/api/offsetbox_api.html