将文本大小转换为数据坐标

时间:2011-06-06 11:48:33

标签: python matplotlib

在matplotlib中,有什么方法可以将文本框大小转换为数据坐标? 例如,在这个玩具脚本中,我正在微调文本框的坐标,使其位于数据点的旁边。

#!/usr/bin/python 
import matplotlib.pyplot as plt

xx=[1,2,3]
yy=[2,3,4]
dy=[0.1,0.2,0.05]

fig=plt.figure()
ax=fig.add_subplot(111)

ax.errorbar(xx,yy,dy,fmt='ro-',ms=6,elinewidth=4)

# HERE: can one get the text bbox size?
txt=ax.text(xx[1]-0.1,yy[1]-0.4,r'$S=0$',fontsize=16)

ax.set_xlim([0.,3.4])
ax.set_ylim([0.,4.4])

plt.show()

有没有办法做这样的伪代码?

x = xx[1] - text_height
y = yy[1] - text_width/2
ax.text(x,y,text)

2 个答案:

答案 0 :(得分:10)

一般来说,在绘制文本之前,你无法获得文本的大小(因此@ DSM的回答是黑客攻击)。

对于您想要做的事情,使用annotate会更好。

E.g。 ax.annotate('Your text string', xy=(x, y), xytext=(x-0.1, y-0.4))

请注意,您也可以在 points 中指定偏移量,从而将文本偏移高度(仅指定textcoords='offset points'

如果您想调整垂直对齐,水平对齐等,只需将这些作为参数添加到annotate(例如horizontalalignment='right'或等效ha='right'

答案 1 :(得分:7)

我对此并不满意,但以下作品;在我找到类似问题的this code之前,我感到很沮丧,这提出了一种获取渲染器的方法。

import matplotlib.pyplot as plt

xx=[1,2,3]
yy=[2,3,4]
dy=[0.1,0.2,0.05]

fig=plt.figure()
figname = "out.png"
ax=fig.add_subplot(111)

ax.errorbar(xx,yy,dy,fmt='ro-',ms=6,elinewidth=4)

# start of hack to get renderer
fig.savefig(figname)
renderer = plt.gca().get_renderer_cache()
# end of hack

txt = ax.text(xx[1], yy[1],r'$S=0$',fontsize=16)
tbox = txt.get_window_extent(renderer)
dbox = tbox.transformed(ax.transData.inverted())
text_width = dbox.x1-dbox.x0
text_height = dbox.y1-dbox.y0
x = xx[1] - text_height
y = yy[1] - text_width/2
txt.set_position((x,y))

ax.set_xlim([0.,3.4])
ax.set_ylim([0.,4.4])

fig.savefig(figname)

OTOH,虽然这可能会从实际数据 point 中取出文本框,但它不一定会使标记的框不受影响,或者错误栏。所以我不知道它在实践中会有多大用处,但我想在所有绘制的对象上循环并移动文本直到它完全消失并不困难。我认为链接代码会尝试类似的东西。

编辑:请注意,这显然是礼貌的接受;如果我真的想这样做,我会使用Joe Kington的解决方案,其他人也应如此。 :^)

相关问题