*边界框内的文本对齐*

时间:2016-01-08 18:39:35

标签: python matplotlib plot

可以使用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')

产生:

enter image description here

是否仍然保持相同的边界框({​​{1}})对齐,同时更改该边界框内文本的对齐方式?,例如使文本在边界框中居中。

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

1 个答案:

答案 0 :(得分: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()
相关问题