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

Skip to content

Commit 279405d

Browse files
authored
Merge pull request #18145 from diegopetrola/issue#17906
Created a parameter fontset that can be used in each Text element
2 parents 682836c + 6fd3a75 commit 279405d

File tree

6 files changed

+139
-9
lines changed

6 files changed

+139
-9
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
===============
3+
Math fontfamily
4+
===============
5+
6+
A simple example showcasing the new *math_fontfamily* parameter that can
7+
be used to change the family of fonts for each individual text
8+
element in a plot.
9+
10+
If no parameter is set, the global value
11+
:rc:`mathtext.fontset` will be used.
12+
"""
13+
14+
import matplotlib.pyplot as plt
15+
16+
plt.figure(figsize=(6, 5))
17+
18+
# A simple plot for the background.
19+
plt.plot(range(11), color="0.9")
20+
21+
# A text mixing normal text and math text.
22+
msg = (r"Normal Text. $Text\ in\ math\ mode:\ "
23+
r"\int_{0}^{\infty } x^2 dx$")
24+
25+
# Set the text in the plot.
26+
plt.text(1, 7, msg, size=12, math_fontfamily='cm')
27+
28+
# Set another font for the next text.
29+
plt.text(1, 3, msg, size=12, math_fontfamily='dejavuserif')
30+
31+
# *math_fontfamily* can be used in most places where there is text,
32+
# like in the title:
33+
plt.title(r"$Title\ in\ math\ mode:\ \int_{0}^{\infty } x^2 dx$",
34+
math_fontfamily='stixsans', size=14)
35+
36+
# Note that the normal text is not changed by *math_fontfamily*.
37+
plt.show()

lib/matplotlib/font_manager.py

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from matplotlib import afm, cbook, ft2font, rcParams
4242
from matplotlib.fontconfig_pattern import (
4343
parse_fontconfig_pattern, generate_fontconfig_pattern)
44+
from matplotlib.rcsetup import _validators
4445

4546
_log = logging.getLogger(__name__)
4647

@@ -624,10 +625,10 @@ class FontProperties:
624625
"""
625626
A class for storing and manipulating font properties.
626627
627-
The font properties are those described in the `W3C Cascading
628-
Style Sheet, Level 1
628+
The font properties are the six properties described in the
629+
`W3C Cascading Style Sheet, Level 1
629630
<http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
630-
specification. The six properties are:
631+
specification and *math_fontfamily* for math fonts:
631632
632633
- family: A list of font names in decreasing order of priority.
633634
The items may include a generic font family name, either
@@ -653,6 +654,12 @@ class FontProperties:
653654
'small', 'medium', 'large', 'x-large', 'xx-large' or an
654655
absolute font size, e.g., 12.
655656
657+
- math_fontfamily: The family of fonts used to render math text; overrides
658+
:rc:`mathtext.fontset`. Supported values are the same as the ones
659+
supported by :rc:`mathtext.fontset` ::
660+
661+
'dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans' and 'custom'.
662+
656663
The default font property for TrueType fonts (as specified in the
657664
default rcParams) is ::
658665
@@ -690,6 +697,7 @@ def __init__(self,
690697
stretch= None,
691698
size = None,
692699
fname = None, # if set, it's a hardcoded filename to use
700+
math_fontfamily = None,
693701
):
694702
self._family = _normalize_font_family(rcParams['font.family'])
695703
self._slant = rcParams['font.style']
@@ -698,6 +706,7 @@ def __init__(self,
698706
self._stretch = rcParams['font.stretch']
699707
self._size = rcParams['font.size']
700708
self._file = None
709+
self._math_fontfamily = None
701710

702711
if isinstance(family, str):
703712
# Treat family as a fontconfig pattern if it is the only
@@ -714,6 +723,7 @@ def __init__(self,
714723
self.set_stretch(stretch)
715724
self.set_file(fname)
716725
self.set_size(size)
726+
self.set_math_fontfamily(math_fontfamily)
717727

718728
@classmethod
719729
def _from_any(cls, arg):
@@ -745,7 +755,8 @@ def __hash__(self):
745755
self.get_weight(),
746756
self.get_stretch(),
747757
self.get_size_in_points(),
748-
self.get_file())
758+
self.get_file(),
759+
self.get_math_fontfamily())
749760
return hash(l)
750761

751762
def __eq__(self, other):
@@ -934,6 +945,45 @@ def set_fontconfig_pattern(self, pattern):
934945
else:
935946
getattr(self, "set_" + key)(val)
936947

948+
def get_math_fontfamily(self):
949+
"""
950+
Return the name of the font family used for math text.
951+
952+
The default font is :rc:`mathtext.fontset`.
953+
"""
954+
if self._math_fontfamily is None:
955+
return rcParams['mathtext.fontset']
956+
return self._math_fontfamily
957+
958+
def set_math_fontfamily(self, fontfamily):
959+
"""
960+
Set the font family for text in math mode.
961+
962+
If not set explicitly, :rc:`mathtext.fontset` will be used.
963+
964+
Parameters
965+
----------
966+
fontfamily : str
967+
The name of the font family.
968+
969+
Available font families are defined in the
970+
matplotlibrc.template file
971+
:ref:`here <customizing-with-matplotlibrc-files>`
972+
973+
See Also
974+
--------
975+
.text.Text.get_math_fontfamily
976+
"""
977+
if fontfamily is None:
978+
self._math_fontfamily = None
979+
return
980+
981+
valid_fonts = _validators['mathtext.fontset'].valid.values()
982+
# _check_in_list() Validates the parameter math_fontfamily as
983+
# if it were passed to rcParams['mathtext.fontset']
984+
cbook._check_in_list(valid_fonts, math_fontfamily=fontfamily)
985+
self._math_fontfamily = fontfamily
986+
937987
def copy(self):
938988
"""Return a copy of self."""
939989
new = type(self)()

lib/matplotlib/mathtext.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3351,12 +3351,10 @@ def parse(self, s, dpi=72, prop=None, *, _force_standard_ps_fonts=False):
33513351
# lru_cache can't decorate parse() directly because the ps.useafm and
33523352
# mathtext.fontset rcParams also affect the parse (e.g. by affecting
33533353
# the glyph metrics).
3354-
return self._parse_cached(s, dpi, prop, _force_standard_ps_fonts,
3355-
rcParams['mathtext.fontset'])
3354+
return self._parse_cached(s, dpi, prop, _force_standard_ps_fonts)
33563355

33573356
@functools.lru_cache(50)
3358-
def _parse_cached(self, s, dpi, prop, force_standard_ps_fonts, fontset):
3359-
3357+
def _parse_cached(self, s, dpi, prop, force_standard_ps_fonts):
33603358
if prop is None:
33613359
prop = FontProperties()
33623360

@@ -3365,7 +3363,8 @@ def _parse_cached(self, s, dpi, prop, force_standard_ps_fonts, fontset):
33653363
else:
33663364
backend = self._backend_mapping[self._output]()
33673365
fontset_class = cbook._check_getitem(
3368-
self._font_type_mapping, fontset=fontset)
3366+
self._font_type_mapping,
3367+
fontset=prop.get_math_fontfamily())
33693368
font_output = fontset_class(prop, backend)
33703369

33713370
fontsize = prop.get_size_in_points()

lib/matplotlib/tests/test_mathtext.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,3 +364,13 @@ def test_mathtext_to_png(tmpdir):
364364
mt = mathtext.MathTextParser('bitmap')
365365
mt.to_png(str(tmpdir.join('example.png')), '$x^2$')
366366
mt.to_png(io.BytesIO(), '$x^2$')
367+
368+
369+
@image_comparison(baseline_images=['math_fontfamily_image.png'],
370+
savefig_kwarg={'dpi': 40})
371+
def test_math_fontfamily():
372+
fig = plt.figure(figsize=(10, 3))
373+
fig.text(0.2, 0.7, r"$This\ text\ should\ have\ one\ font$",
374+
size=24, math_fontfamily='dejavusans')
375+
fig.text(0.2, 0.3, r"$This\ text\ should\ have\ another$",
376+
size=24, math_fontfamily='stix')

lib/matplotlib/text.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1061,6 +1061,40 @@ def set_fontsize(self, fontsize):
10611061
self._fontproperties.set_size(fontsize)
10621062
self.stale = True
10631063

1064+
def get_math_fontfamily(self):
1065+
"""
1066+
Return the font family name for math text rendered by Matplotlib.
1067+
1068+
The default value is :rc:`mathtext.fontset`.
1069+
1070+
See Also
1071+
--------
1072+
set_math_fontfamily
1073+
"""
1074+
return self._fontproperties.get_math_fontfamily()
1075+
1076+
def set_math_fontfamily(self, fontfamily):
1077+
"""
1078+
Set the font family for math text rendered by Matplotlib.
1079+
1080+
This does only affect Matplotlib's own math renderer. It has no effect
1081+
when rendering with TeX (``usetex=True``).
1082+
1083+
Parameters
1084+
----------
1085+
fontfamily : str
1086+
The name of the font family.
1087+
1088+
Available font families are defined in the
1089+
:ref:`matplotlibrc.template file
1090+
<customizing-with-matplotlibrc-files>`.
1091+
1092+
See Also
1093+
--------
1094+
get_math_fontfamily
1095+
"""
1096+
self._fontproperties.set_math_fontfamily(fontfamily)
1097+
10641098
def set_fontweight(self, weight):
10651099
"""
10661100
Set the font weight.

0 commit comments

Comments
 (0)