tensor-sensor

Форк
0
/
str_size_matplotlib.py 
89 строк · 2.7 Кб
1
import matplotlib as mpl
2
import matplotlib.patches as patches
3
from matplotlib import pyplot as plt
4

5
def textdim(s, fontname='Consolas', fontsize=11):
6
    fig, ax = plt.subplots(1,1)
7
    t = ax.text(0, 0, s, bbox={'lw':0, 'pad':0}, fontname=fontname, fontsize=fontsize)
8
    # plt.savefig(tempfile.mktemp(".pdf"))
9
    plt.savefig("/tmp/font.pdf", pad_inches=0, dpi=200)
10
    print(t)
11
    plt.close()
12
    bb = t.get_bbox_patch()
13
    print(bb)
14
    w, h = bb.get_width(), bb.get_height()
15
    return 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
22
def find_renderer(fig):
23
    if hasattr(fig.canvas, "get_renderer"):
24
        #Some backends, such as TkAgg, have the get_renderer method, which
25
        #makes this easy.
26
        renderer = fig.canvas.get_renderer()
27
    else:
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.)
33
        import io
34
        fig.canvas.print_pdf(io.BytesIO())
35
        renderer = fig._cachedRenderer
36
    return(renderer)
37

38

39
def textdim(s, fontname='Consolas', fontsize=11):
40
    fig, ax = plt.subplots(1, 1)
41
    t = ax.text(0, 0, s, fontname=fontname, fontsize=fontsize, transform=None)
42
    bb = t.get_window_extent(find_renderer(fig))
43
    print(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)
48
    plt.close()
49
    return 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

55
code = 'W@ b + x *3 + h.dot(h)'
56
code = 'W@ b.f(x,y)'# + x *3 + h.dot(h)'
57

58
fig, ax = plt.subplots(1,1,figsize=(4,1))
59

60
fontname = "Serif"
61
fontsize = 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

72
x = 0
73
for c in code:
74
    # print(f"plot {c} at {x},{0}")
75
    ax.text(x, 10, c, fontname=fontname, fontsize=fontsize, transform=None)
76
    w, h = textdim(c, fontname=fontname, fontsize=fontsize)
77
    # print(w,h,'->',x)
78
    x = x + w
79

80
ax.set_xlim(0,x)
81
#ax.set_ylim(0,10)
82

83
ax.axis('off')
84

85
#plt.show()
86

87
plt.tight_layout()
88

89
plt.savefig("/tmp/t.pdf", bbox_inches='tight', pad_inches=0, dpi=200)
90

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.