DilithiumMatrix
DilithiumMatrix

Reputation: 18677

Text alignment *within* bounding box

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

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:

enter image description here

Is there anyway to keep the same bounding-box (bbox) alignment, while changing the alignment of the text within that bounding-box? e.g. 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.)

Upvotes: 4

Views: 1671

Answers (1)

Niemerds
Niemerds

Reputation: 942

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

Printed Output

original bbox (figure system)   : Bbox(x0=0.7000000000000001, y0=0.467946875, x1=0.84201171875, y1=0.532053125)
aligned bbox            : Bbox(x0=0.55798828125, y0=0.467946875, x1=0.7000000000000001, y1=0.532053125)
shifted bbox            : Bbox(x0=0.7000000000000002, y0=0.467946875, x1=0.8420117187500001, y1=0.532053125)

enter image description here

Upvotes: 2

Related Questions