确切的 bbox 取决于特定后端的渲染器。以下示例保留文本 bbox 的 x 位置。精确地保留 x 和 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()
打印输出
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)