Last active
February 11, 2022 23:12
-
-
Save anntzer/9eebceab758440e61ec90ddfdd726ff7 to your computer and use it in GitHub Desktop.
fixed width bbox around text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import partial | |
import matplotlib as mpl | |
from matplotlib import pyplot as plt | |
def patched_update_bbox_position_size(text, renderer): | |
# Absolutely zero guarantees that the internally returned value will not | |
# change in future versions! | |
orig_get_layout = text._get_layout | |
def tmp_patched_get_layout(renderer): | |
_1, layout, _2 = orig_get_layout(renderer) | |
for i, (t, (w, h), x, y) in enumerate(layout): | |
# force the patch width (w=100) and pretend that the text starts at x=-50 | |
layout[i] = (t, (100, h), -50, y) | |
return _1, layout, _2 | |
text._get_layout = tmp_patched_get_layout | |
mpl.text.Text.update_bbox_position_size(text, renderer) # call base method | |
text._get_layout = orig_get_layout | |
fig = plt.figure() | |
t1 = fig.text(.5, .9, "hello", ha="center", bbox={}) | |
t2 = fig.text(.5, .8, "world!", ha="center", bbox={}) | |
t3 = fig.text(.5, .7, "draw", ha="center", bbox={}) | |
t4 = fig.text(.5, .6, "fixed-width", ha="center", bbox={}) | |
t5 = fig.text(.5, .5, "rectangles", ha="center", bbox={}) | |
t3.update_bbox_position_size = partial(patched_update_bbox_position_size, t3) | |
t4.update_bbox_position_size = partial(patched_update_bbox_position_size, t4) | |
t5.update_bbox_position_size = partial(patched_update_bbox_position_size, t5) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment