matplotlib measure the width of text

Solutions on MaxInterview for matplotlib measure the width of text by the best coders in the world

showing results for - "matplotlib measure the width of text"
Camilla
21 Jan 2020
1import matplotlib.pyplot as plt
2
3# some example plot
4plt.plot([1,2,3], [2,3,4])
5
6t = plt.text(1.1, 3.1, "my text", fontsize=18)
7
8# to get the text bounding box 
9# we need to draw the plot
10plt.gcf().canvas.draw()
11
12
13# get bounding box of the text 
14# in the units of the data
15bbox = t.get_window_extent()\
16    .inverse_transformed(plt.gca().transData)
17
18
19print(bbox)
20# prints: Bbox(x0=1.1, y0=3.0702380952380954, x1=1.5296875, y1=3.2130952380952382)
21
22
23# plot the bounding box around the text
24plt.plot([bbox.x0, bbox.x0, bbox.x1, bbox.x1, bbox.x0],
25         [bbox.y0, bbox.y1, bbox.y1, bbox.y0, bbox.y0])
26
27plt.show()
Carla
05 Aug 2018
1from matplotlib import pyplot as plt
2
3f = plt.figure()
4r = f.canvas.get_renderer()
5t = plt.text(0.5, 0.5, 'test')
6
7bb = t.get_window_extent(renderer=r)
8width = bb.width
9height = bb.height