The relevant call is
txt.get_window_extent()
if txt
is an Text-object as returned by plt.text
.
It is important to draw the figure before getting the extents, as it is not calculated before. An complete example would be:
import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy
fig = plt.figure()
ax = plt.axes()
txt = plt.text(0.1,0.5,"My text", transform = ax.transAxes)
fig.canvas.draw()
text_bbox = txt.get_window_extent()
transform_for_second_text = offset_copy(ax.transAxes, fig,
x=text_bbox.width,
units="dots")
plt.text(0.1,0.5, "Second text", transform=transform_for_second_text, color="r")
plt.show()
resulting in:
Please note that fig.canvas.draw()
is an quite expensive operation, so don't do this too often, e.g., first create all white texts, then draw the figure canvas, and then create all red texts.