This may help a bit.
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.plot([0,10], [4,0])
t = ax.text(3.2, 2.1, "testing...")
# get the inverse of the transformation from data coordinates to pixels
transf = ax.transData.inverted()
bb = t.get_window_extent(renderer = f.canvas.renderer)
bb_datacoords = bb.transformed(transf)
# Bbox('array([[ 3.2 , 2.1 ],
[ 4.21607125, 2.23034396]])')
This should give what you want. If you want to have the coordinates in terms of figure coordinates (0..1,0..1), then use the inverse of ax.transAxes
.
However, there is a small catch in this solution. An excerpt from the matplotlib
documentation:
Any Text instance can report its extent in window coordinates (a negative x coordinate is outside the window), but there is a rub.
The RendererBase instance, which is used to calculate the text size, is not known until the figure is drawn (draw()). After the window is drawn and the text instance knows its renderer, you can call get_window_extent().
So, before the figure is really drawn, there seems to be no way to find out the text size.
BTW, you may have noticed that the Bbox
instances have method overlaps
which may be used to find out whether the Bbox
overlaps with another one (bb1.overlaps(bb2)
). This may be useful in some cases, but it does not answer the question "how much".
If you have rotated texts, you will have hard time seeing if they overlap, but that you probably already know.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…