Convert text size to data coordinates

In matplotlib, what is the way to convert textbox size to data coordinates? For example, in this toy script, I fine-tune the coordinates of the text field so that it is next to the data point.

#!/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() 

Is there a way to do something like this pseudocode?

 x = xx[1] - text_height y = yy[1] - text_width/2 ax.text(x,y,text) 
+6
source share
2 answers

I do not like this at all, but the following works; I was upset until I found this code for a similar problem, which suggested a way to get the rendering.

 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, while this may infer a text field from the actual data point, this does not necessarily result in the field not being marked with a marker or error bar. Therefore, I do not know how useful this is in practice, but I think it would be difficult to iterate over all the drawn objects and move the text until it is on the sidelines. I think the linked code is trying something like this.

Edit: Please note that this was clearly taken with courtesy; I would use Joe Kington's solution if I really wanted to do this, and everyone else.: ^)

+6
source

Generally speaking, you cannot get the size of the text until it is drawn (thus, hacks in @DSM's answer).

For what you want to do, you will be much better off using annotate .

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

Please note that you can also specify the offset in points and thus offset the text in height (just specify textcoords='offset points' )

If you want to adjust vertical alignment, horizontal alignment, etc. just add them as arguments to annotate (e.g. horizontalalignment='right' or equivalent to ha='right' )

+10
source

Source: https://habr.com/ru/post/889862/


All Articles