简体   繁体   中英

Text alignment *within* bounding box

The alignment of a text box can be specified with the horizontalalignment ( ha ) and verticalalignment ( va ) arguments, eg

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')

Which produces:

在此输入图像描述

Is there anyway to keep the same bounding-box ( bbox ) alignment, while changing the alignment of the text within that bounding-box? eg for the text to be centered in the bounding-box.

(Obviously in this situation I could just replace the bounding-box, but in more complicated cases I'd like to change the text alignment independently.)

The exact bbox depends on the renderer of your specific backend. The following example preserves the x position of the text bbox. It is a bit trickier to exactly preserve both x and 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM