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

标签 python matplotlib plot

文本框的对齐方式可以用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/

相关文章:

python - 将图像添加到绘图 -matplotlib PYTHON

python - 重要的包和模块与 py2exe 不兼容?

python - Matplotlib x 轴标签对齐关闭

plot - 如何创建具有不同 bin 宽度的直方图

python - 允许用户输入 python 的 __import__ 会存在安全风险吗?

用于解析程序中标识符的 Python 包(C、Scala、Lisp)?

python - 用于规范化sklearn SVM输入的正确功能

python - 与之前的结果重复映射

python - 在曲面图上画线

python - Pandas 数据框作为字符串连接连接/合并为单列,便宜