文本对齐 *在* 边界框内部

4
文本框的对齐方式可以通过指定水平对齐(ha)和垂直对齐(va)参数来实现,例如:
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')

产生的结果如下:

enter image description here

有没有办法在改变边界框内文本对齐方式的同时保持相同的边界框对齐(bbox)?例如,使文本在边界框中居中。

(显然,在这种情况下,我可以只替换边界框,但在更复杂的情况下,我想独立地更改文本对齐方式。)

1个回答

2

精确的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()

这仍然会改变整个边界框,而不仅仅是其中的文本。 - DilithiumMatrix
有趣,谢谢。这基本上是我一直在使用的方法(除了我没有看到inverted方法进行转换 - 真的很酷!)。我猜这里没有内置的方法。 - DilithiumMatrix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接