tensor-sensor
89 строк · 2.7 Кб
1import matplotlib as mpl
2import matplotlib.patches as patches
3from matplotlib import pyplot as plt
4
5def textdim(s, fontname='Consolas', fontsize=11):
6fig, ax = plt.subplots(1,1)
7t = ax.text(0, 0, s, bbox={'lw':0, 'pad':0}, fontname=fontname, fontsize=fontsize)
8# plt.savefig(tempfile.mktemp(".pdf"))
9plt.savefig("/tmp/font.pdf", pad_inches=0, dpi=200)
10print(t)
11plt.close()
12bb = t.get_bbox_patch()
13print(bb)
14w, h = bb.get_width(), bb.get_height()
15return w, h
16
17# print(textdim("@"))
18#exit()
19
20
21# From: https://stackoverflow.com/questions/22667224/matplotlib-get-text-bounding-box-independent-of-backend
22def find_renderer(fig):
23if hasattr(fig.canvas, "get_renderer"):
24#Some backends, such as TkAgg, have the get_renderer method, which
25#makes this easy.
26renderer = fig.canvas.get_renderer()
27else:
28#Other backends do not have the get_renderer method, so we have a work
29#around to find the renderer. Print the figure to a temporary file
30#object, and then grab the renderer that was used.
31#(I stole this trick from the matplotlib backend_bases.py
32#print_figure() method.)
33import io
34fig.canvas.print_pdf(io.BytesIO())
35renderer = fig._cachedRenderer
36return(renderer)
37
38
39def textdim(s, fontname='Consolas', fontsize=11):
40fig, ax = plt.subplots(1, 1)
41t = ax.text(0, 0, s, fontname=fontname, fontsize=fontsize, transform=None)
42bb = t.get_window_extent(find_renderer(fig))
43print(s, bb.width, bb.height)
44
45# t = mpl.textpath.TextPath(xy=(0, 0), s=s, size=fontsize, prop=fontname)
46# bb = t.get_extents()
47# print(s, "new", bb)
48plt.close()
49return bb.width, bb.height
50
51# print(textdim("test of foo", fontsize=11))
52# print(textdim("test of foO", fontsize=11))
53# print(textdim("W @ b + x * 3 + h.dot(h)", fontsize=12))
54
55code = 'W@ b + x *3 + h.dot(h)'
56code = 'W@ b.f(x,y)'# + x *3 + h.dot(h)'
57
58fig, ax = plt.subplots(1,1,figsize=(4,1))
59
60fontname = "Serif"
61fontsize = 16
62
63# for c in code:
64# t = ax.text(0,0,c)
65# bbox1 = t.get_window_extent(find_renderer(fig))
66# # print(c, '->', bbox1.width, bbox1.height)
67# print(c, '->', textdim(c, fontname=fontname, fontsize=fontsize))
68# rect1 = patches.Rectangle((0,0), bbox1.width, bbox1.height, \
69# color = [0,0,0], fill = False)
70# fig.patches.append(rect1)
71
72x = 0
73for c in code:
74# print(f"plot {c} at {x},{0}")
75ax.text(x, 10, c, fontname=fontname, fontsize=fontsize, transform=None)
76w, h = textdim(c, fontname=fontname, fontsize=fontsize)
77# print(w,h,'->',x)
78x = x + w
79
80ax.set_xlim(0,x)
81#ax.set_ylim(0,10)
82
83ax.axis('off')
84
85#plt.show()
86
87plt.tight_layout()
88
89plt.savefig("/tmp/t.pdf", bbox_inches='tight', pad_inches=0, dpi=200)
90