The exact bbox depends on the renderer of your specific backend. The following example preserves the x position of the text bbox. It is a bit trickier to exactly preserve both x and y:
import matplotlib
import matplotlib.pyplot as plt
def get_bbox(txt):
renderer = matplotlib.backend_bases.RendererBase()
return txt.get_window_extent(renderer)
fig, ax = plt.subplots(figsize=(8,5))
plt.subplots_adjust(right=0.5)
txt = "Test:\nthis is some text\ninside a bounding box."
text_inst = fig.text(0.7, 0.5, txt, ha='left', va='center')
bbox = get_bbox(text_inst)
bbox_fig = bbox.transformed(fig.transFigure.inverted())
print("original bbox (figure system)\t:", bbox.transformed(fig.transFigure.inverted()))
# adjust horizontal alignment
text_inst.set_ha('right')
bbox_new = get_bbox(text_inst)
bbox_new_fig = bbox_new.transformed(fig.transFigure.inverted())
print("aligned bbox\t\t\t:", bbox_new_fig)
# shift back manually
offset = bbox_fig.x0 - bbox_new_fig.x0
text_inst.set_x(bbox_fig.x0 + offset)
bbox_shifted = get_bbox(text_inst)
print("shifted bbox\t\t\t:", bbox_shifted.transformed(fig.transFigure.inverted()))
plt.show()
Printed Output
original bbox (figure system) : Bbox(x0=0.7000000000000001, y0=0.467946875, x1=0.84201171875, y1=0.532053125)
aligned bbox : Bbox(x0=0.55798828125, y0=0.467946875, x1=0.7000000000000001, y1=0.532053125)
shifted bbox : Bbox(x0=0.7000000000000002, y0=0.467946875, x1=0.8420117187500001, y1=0.532053125)
