8000 Update the font_table example. · matplotlib/matplotlib@c5c6fe9 · GitHub
[go: up one dir, main page]

Skip to content

Commit c5c6fe9

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 c5c6fe9

File tree

2 files changed

+106
-66
lines changed

2 files changed

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