Skip to content

Commit d86660b

Browse files
committed
pgf: Support any font in a collection
Note, this only has an effect if set as the global font. Otherwise, just the font name is recorded, and the TeX engine's normal lookup is performed.
1 parent 1bc92f0 commit d86660b

File tree

3 files changed

+33
-12
lines changed

3 files changed

+33
-12
lines changed

lib/matplotlib/backends/backend_pgf.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,17 @@
3838

3939
def _get_preamble():
4040
"""Prepare a LaTeX preamble based on the rcParams configuration."""
41-
font_size_pt = FontProperties(
42-
size=mpl.rcParams["font.size"]
43-
).get_size_in_points()
41+
def _to_fontspec():
42+
for command, family in [("setmainfont", "serif"),
43+
("setsansfont", "sans\\-serif"),
44+
("setmonofont", "monospace")]:
45+
font_path = fm.findfont(family)
46+
path = pathlib.Path(font_path)
47+
yield r" \%s{%s}[Path=\detokenize{%s/}%s]" % (
48+
command, path.name, path.parent.as_posix(),
49+
f',FontIndex={font_path.face_index:d}' if path.suffix == '.ttc' else '')
50+
51+
font_size_pt = FontProperties(size=mpl.rcParams["font.size"]).get_size_in_points()
4452
return "\n".join([
4553
# Remove Matplotlib's custom command \mathdefault. (Not using
4654
# \mathnormal instead since this looks odd with Computer Modern.)
@@ -63,15 +71,8 @@ def _get_preamble():
6371
*([
6472
r"\ifdefined\pdftexversion\else % non-pdftex case.",
6573
r" \usepackage{fontspec}",
66-
] + [
67-
r" \%s{%s}[Path=\detokenize{%s/}]"
68-
% (command, path.name, path.parent.as_posix())
69-
for command, path in zip(
70-
["setmainfont", "setsansfont", "setmonofont"],
71-
[pathlib.Path(fm.findfont(family))
72-
for family in ["serif", "sans\\-serif", "monospace"]]
73-
)
74-
] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
74+
*_to_fontspec(),
75+
r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
7576
# Documented as "must come last".
7677
mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"),
7778
])
Binary file not shown.

lib/matplotlib/tests/test_backend_pgf.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
import datetime
22
from io import BytesIO
33
import os
4+
from pathlib import Path
45
import shutil
6+
import string
57

68
import numpy as np
79
from packaging.version import parse as parse_version
810
import pytest
911

1012
import matplotlib as mpl
1113
import matplotlib.pyplot as plt
14+
from matplotlib.font_manager import FontProperties, findfont
1215
from matplotlib.testing import _has_tex_package, _check_for_pgf
1316
from matplotlib.testing.exceptions import ImageComparisonFailure
1417
from matplotlib.testing.compare import compare_images
@@ -330,6 +333,23 @@ def test_png_transparency(): # Actually, also just testing that png works.
330333
assert (t[..., 3] == 0).all() # fully transparent.
331334

332335

336+
@needs_pgf_xelatex
337+
@pytest.mark.backend('pgf')
338+
@image_comparison(['ttc_pgf.pdf'], style='mpl20')
339+
def test_ttc_output():
340+
fp = FontProperties(family=['WenQuanYi Zen Hei'])
341+
if Path(findfont(fp)).name != 'wqy-zenhei.ttc':
342+
pytest.skip('Font wqy-zenhei.ttc may be missing')
343+
344+
fonts = {'sans-serif': 'WenQuanYi Zen Hei', 'monospace': 'WenQuanYi Zen Hei Mono'}
345+
plt.rc('font', size=16, **fonts)
346+
347+
figs = plt.figure(figsize=(7, len(fonts) / 2)).subfigures(len(fonts))
348+
for font, fig in zip(fonts.values(), figs):
349+
fig.text(0.5, 0.5, f'{font}: {string.ascii_uppercase}', font=font,
350+
horizontalalignment='center', verticalalignment='center')
351+
352+
333353
@needs_pgf_xelatex
334354
def test_unknown_font(caplog):
335355
with caplog.at_level("WARNING"):

0 commit comments

Comments
 (0)