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

# some example plot
plt.plot([1,2,3], [2,3,4])

t = plt.text(1.1, 3.1, "my text", fontsize=18)

# to get the text bounding box 
# we need to draw the plot
plt.gcf().canvas.draw()


# get bounding box of the text 
# in the units of the data
bbox = t.get_window_extent()\
    .inverse_transformed(plt.gca().transData)


print(bbox)
# prints: Bbox(x0=1.1, y0=3.0702380952380954, x1=1.5296875, y1=3.2130952380952382)


# plot the bounding box around the text
plt.plot([bbox.x0, bbox.x0, bbox.x1, bbox.x1, bbox.x0],
         [bbox.y0, bbox.y1, bbox.y1, bbox.y0, bbox.y0])

plt.show()