gpt4 book ai didi

python - 文本对齐*在*边界框内

转载 作者:行者123 更新时间:2023-11-28 17:30:33 25 4
gpt4 key购买 nike

文本框的对齐方式可以用horizo​​ntalalignment (ha) 和verticalalignment (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) 对齐方式,同时更改该边界框内文本的对齐方式? 例如使文本在边界框中居中。

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

最佳答案

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

关于python - 文本对齐*在*边界框内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34683864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com