matplotlib get padding from bbox

Solutions on MaxInterview for matplotlib get padding from bbox by the best coders in the world

showing results for - "matplotlib get padding from bbox"
Cristóbal
29 May 2020
1import matplotlib
2matplotlib.rc('text',usetex=True)
3import matplotlib.pyplot as plt
4from matplotlib.patches import Rectangle
5import numpy as np
6
7text = '\\begin{tabular}{|c|c|}\\hline1&2\\\\\\hline3&4\\\\\\hline\\end{tabular}'
8
9fig, ax = plt.subplots(1)
10
11img = ax.imshow(np.zeros((10,10)), cmap=plt.cm.gray)
12txt = ax.text( 4.5,
13          4.5,
14          text,
15          fontsize=24,
16          ha='center',
17          va='center',
18          bbox=dict(alpha=0))
19
20fig.canvas.draw()
21bbox = txt.get_bbox_patch()
22xmin = bbox.get_window_extent().xmin
23xmax = bbox.get_window_extent().xmax
24ymin = bbox.get_window_extent().ymin
25ymax = bbox.get_window_extent().ymax
26
27xmin, ymin = fig.transFigure.inverted().transform((xmin, ymin))
28xmax, ymax = fig.transFigure.inverted().transform((xmax, ymax))
29
30dx = xmax-xmin
31dy = ymax-ymin
32
33# The bounding box vals can be tweaked manually here.
34rect = Rectangle((xmin-0.02,ymin-0.01), dx+0.04, dy+0.05, fc='w', transform=fig.transFigure)
35
36ax.add_patch(rect)
37fig.canvas.draw()
38ax.axis('off')
39plt.savefig('ok.png',bbox_inches='tight')
40
41
42
43
44
similar questions
queries leading to this page
matplotlib get padding from bbox