matplotlib measure the width of text code example
Example 1: matplotlib measure the width of text
from matplotlib import pyplot as plt
f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0.5, 0.5, 'test')
bb = t.get_window_extent(renderer=r)
width = bb.width
height = bb.height
Example 2: matplotlib measure the width of text
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,4])
t = plt.text(1.1, 3.1, "my text", fontsize=18)
plt.gcf().canvas.draw()
bbox = t.get_window_extent()\
.inverse_transformed(plt.gca().transData)
print(bbox)
plt.plot([bbox.x0, bbox.x0, bbox.x1, bbox.x1, bbox.x0],
[bbox.y0, bbox.y1, bbox.y1, bbox.y0, bbox.y0])
plt.show()