matplotlib 文本对齐方式 * 在 * 边界框内

5ssjco0h  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(152)

文本框的对齐方式可以用horizontalalignmentha)和verticalalignmentva)参数指定,例如

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,5))
plt.subplots_adjust(right=0.5)
txt = "Test:\nthis is some text\ninside a bounding box."
fig.text(0.7, 0.5, txt, ha='left', va='center')

字符串
它产生:
x1c 0d1x的数据

**是否有办法保持相同的边界框(bbox)对齐方式,同时更改该边界框内的文本对齐方式?**例如,文本在边界框中居中。

(显然,在这种情况下,我可以直接替换bounding-box,但在更复杂的情况下,我希望独立更改文本对齐方式。)

zxlwwiss

zxlwwiss1#

确切的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)


的数据

相关问题