Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e3e06a7

Browse files
committed
Update the font_table example.
Print characters corresponding to codepoints >0xff. Add comments explaining font charmaps (briefly). Don't use pyplot.
1 parent 99d8900 commit e3e06a7

2 files changed

Lines changed: 104 additions & 66 deletions

File tree

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
"""
2+
==========
3+
Font table
4+
==========
5+
6+
Matplotlib's font support is provided by the FreeType library.
7+
8+
Here, we use `~.Axes.table` build a font table that shows the glyphs by Unicode
9+
codepoint, and print the glyphs corresponding to codepoints beyond 0xff.
10+
11+
Download this script and run it to investigate a font by running ::
12+
13+
python font_table_sgskip.py /path/to/font/file
14+
"""
15+
16+
import unicodedata
17+
18+
import matplotlib.font_manager as fm
19+
from matplotlib.ft2font import FT2Font
20+
import matplotlib.pyplot as plt
21+
import numpy as np
22+
23+
24+
def draw_font_table(path):
25+
"""
26+
Parameters
27+
----------
28+
path : str or None
29+
The path to the font file. If None, use Matplotlib's default font.
30+
"""
31+
32+
if path is None:
33+
path = fm.findfont(fm.FontProperties()) # The default font.
34+
35+
font = FT2Font(path)
36+
# A charmap is a mapping of "character codes" (in the sense of a character
37+
# encoding, e.g. latin-1) to glyph indices (i.e. the internal storage table
38+
# of the font face).
39+
# In FreeType>=2.1, a Unicode charmap (i.e. mapping Unicode codepoints)
40+
# is selected by default. Moreover, recent versions of FreeType will
41+
# automatically synthesize such a charmap if the font does not include one
42+
# (this behavior depends on the font format; for example it is present
43+
# since FreeType 2.0 for Type 1 fonts but only since FreeType 2.8 for
44+
# TrueType (actually, SFNT) fonts).
45+
# The code below (specifically, the ``chr(char_code)`` call) assumes that
46+
# we have indeed selected a Unicode charmap.
47+
codes = font.get_charmap().items()
48+
49+
labelc = ["{:X}".format(i) for i in range(16)]
50+
labelr = ["{:02X}".format(16 * i) for i in range(16)]
51+
chars = [["" for c in range(16)] for r in range(16)]
52+
non_8bit = []
53+
54+
for char_code, glyph_index in codes:
55+
char = chr(char_code)
56+
if char_code >= 256:
57+
non_8bit.append((
58+
str(glyph_index),
59+
char,
60+
unicodedata.name(
61+
char,
62+
f"{char_code:#x} ({font.get_glyph_name(glyph_index)})"),
63+
))
64+
continue
65+
r, c = divmod(char_code, 16)
66+
chars[r][c] = char
67+
if non_8bit:
68+
indices, *_ = zip(*non_8bit)
69+
max_indices_len = max(map(len, indices))
70+
print("The font face contains the following glyphs corresponding to "
71+
"code points beyond 0xff:")
72+
for index, char, name in non_8bit:
73+
print(f"{index:>{max_indices_len}} {char} {name}")
74+
75+
ax = plt.figure(figsize=(8, 4), dpi=120).subplots()
76+
ax.set_title(path)
77+
ax.set_axis_off()
78+
79+
table = ax.table(
80+
cellText=chars,
81+
rowLabels=labelr,
82+
colLabels=labelc,
83+
rowColours=["palegreen"] * 16,
84+
colColours=["palegreen"] * 16,
85+
cellColours=[[".95" for c in range(16)] for r in range(16)],
86+
cellLoc='center',
87+
loc='upper left',
88+
)
89+
for key, cell in table.get_celld().items():
90+
row, col = key
91+
if row > 0 and col > -1: # Beware of table's idiosyncratic indexing...
92+
cell.set_text_props(fontproperties=fm.FontProperties(fname=path))
93+
94+
plt.show()
95+
96+
97+
if __name__ == "__main__":
98+
from argparse import ArgumentParser
99+
100+
parser = ArgumentParser()
101+
parser.add_argument("path", nargs="?", help="Path to the font file.")
102+
args = parser.parse_args()
103+
104+
draw_font_table(args.path)

examples/text_labels_and_annotations/font_table_ttf_sgskip.py

Lines changed: 0 additions & 66 deletions
This file was deleted.

0 commit comments

Comments
 (0)