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

Skip to content

Commit 508f21f

Browse files
authored
Merge pull request #15695 from anntzer/mathdefault
Define \mathdefault as a noop in the usetex preamble.
2 parents 9344cb4 + 7ccccc0 commit 508f21f

File tree

3 files changed

+44
-70
lines changed

3 files changed

+44
-70
lines changed

lib/matplotlib/tests/test_usetex.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,15 @@
66
import matplotlib.pyplot as plt
77

88

9-
@pytest.fixture(autouse=True) # All tests in this module use usetex.
10-
def usetex():
11-
if not mpl.checkdep_usetex(True):
12-
pytest.skip('Missing TeX of Ghostscript or dvipng')
13-
mpl.rcParams['text.usetex'] = True
9+
if not mpl.checkdep_usetex(True):
10+
pytestmark = pytest.mark.skip('Missing TeX of Ghostscript or dvipng')
1411

1512

1613
@image_comparison(baseline_images=['test_usetex'],
1714
extensions=['pdf', 'png'],
1815
tol={'aarch64': 2.868}.get(platform.machine(), 0.3))
1916
def test_usetex():
17+
mpl.rcParams['text.usetex'] = True
2018
fig = plt.figure()
2119
ax = fig.add_subplot(111)
2220
ax.text(0.1, 0.2,
@@ -32,5 +30,16 @@ def test_usetex():
3230

3331
@check_figures_equal()
3432
def test_unicode_minus(fig_test, fig_ref):
33+
mpl.rcParams['text.usetex'] = True
3534
fig_test.text(.5, .5, "$-$")
3635
fig_ref.text(.5, .5, "\N{MINUS SIGN}")
36+
37+
38+
def test_mathdefault():
39+
plt.rcParams["axes.formatter.use_mathtext"] = True
40+
fig = plt.figure()
41+
fig.add_subplot().set_xlim(-1, 1)
42+
# Check that \mathdefault commands generated by tickers don't cause
43+
# problems when later switching usetex on.
44+
mpl.rcParams['text.usetex'] = True
45+
fig.canvas.draw()

lib/matplotlib/texmanager.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,22 @@ def get_custom_preamble(self):
192192
"""Return a string containing user additions to the tex preamble."""
193193
return rcParams['text.latex.preamble']
194194

195+
def _get_preamble(self):
196+
unicode_preamble = "\n".join([
197+
r"\usepackage[utf8]{inputenc}",
198+
r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
199+
]) if rcParams["text.latex.unicode"] else ""
200+
return "\n".join([
201+
r"\documentclass{article}",
202+
# Pass-through \mathdefault, which is used in non-usetex mode to
203+
# use the default text font but was historically suppressed in
204+
# usetex mode.
205+
r"\newcommand{\mathdefault}[1]{#1}",
206+
self._font_preamble,
207+
unicode_preamble,
208+
self.get_custom_preamble(),
209+
])
210+
195211
def make_tex(self, tex, fontsize):
196212
"""
197213
Generate a tex file to render the tex string at a specific font size.
@@ -200,29 +216,19 @@ def make_tex(self, tex, fontsize):
200216
"""
201217
basefile = self.get_basefile(tex, fontsize)
202218
texfile = '%s.tex' % basefile
203-
custom_preamble = self.get_custom_preamble()
204219
fontcmd = {'sans-serif': r'{\sffamily %s}',
205220
'monospace': r'{\ttfamily %s}'}.get(self.font_family,
206221
r'{\rmfamily %s}')
207222
tex = fontcmd % tex
208223

209-
unicode_preamble = "\n".join([
210-
r"\usepackage[utf8]{inputenc}",
211-
r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
212-
]) if rcParams["text.latex.unicode"] else ""
213-
214224
s = r"""
215-
\documentclass{article}
216-
%s
217-
%s
218225
%s
219226
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
220227
\pagestyle{empty}
221228
\begin{document}
222229
\fontsize{%f}{%f}%s
223230
\end{document}
224-
""" % (self._font_preamble, unicode_preamble, custom_preamble,
225-
fontsize, fontsize * 1.25, tex)
231+
""" % (self._get_preamble(), fontsize, fontsize * 1.25, tex)
226232
with open(texfile, 'wb') as fh:
227233
if rcParams['text.latex.unicode']:
228234
fh.write(s.encode('utf8'))
@@ -250,24 +256,15 @@ def make_tex_preview(self, tex, fontsize):
250256
"""
251257
basefile = self.get_basefile(tex, fontsize)
252258
texfile = '%s.tex' % basefile
253-
custom_preamble = self.get_custom_preamble()
254259
fontcmd = {'sans-serif': r'{\sffamily %s}',
255260
'monospace': r'{\ttfamily %s}'}.get(self.font_family,
256261
r'{\rmfamily %s}')
257262
tex = fontcmd % tex
258263

259-
unicode_preamble = "\n".join([
260-
r"\usepackage[utf8]{inputenc}",
261-
r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
262-
]) if rcParams["text.latex.unicode"] else ""
263-
264264
# newbox, setbox, immediate, etc. are used to find the box
265265
# extent of the rendered text.
266266

267267
s = r"""
268-
\documentclass{article}
269-
%s
270-
%s
271268
%s
272269
\usepackage[active,showbox,tightpage]{preview}
273270
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
@@ -282,8 +279,7 @@ def make_tex_preview(self, tex, fontsize):
282279
{\fontsize{%f}{%f}%s}
283280
\end{preview}
284281
\end{document}
285-
""" % (self._font_preamble, unicode_preamble, custom_preamble,
286-
fontsize, fontsize * 1.25, tex)
282+
""" % (self._get_preamble(), fontsize, fontsize * 1.25, tex)
287283
with open(texfile, 'wb') as fh:
288284
if rcParams['text.latex.unicode']:
289285
fh.write(s.encode('utf8'))

lib/matplotlib/ticker.py

Lines changed: 12 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,6 @@
188188
'SymmetricalLogLocator', 'LogitLocator', 'OldAutoLocator')
189189

190190

191-
def _mathdefault(s):
192-
return '\\mathdefault{%s}' % s
193-
194-
195191
class _DummyAxis:
196192
def __init__(self, minpos=0):
197193
self.dataLim = mtransforms.Bbox.unit()
@@ -654,14 +650,10 @@ def get_offset(self):
654650
sciNotStr = self.format_data(10 ** self.orderOfMagnitude)
655651
else:
656652
sciNotStr = '1e%d' % self.orderOfMagnitude
657-
if self._useMathText:
658-
if sciNotStr != '':
659-
sciNotStr = r'\times%s' % _mathdefault(sciNotStr)
660-
s = ''.join(('$', sciNotStr, _mathdefault(offsetStr), '$'))
661-
elif self._usetex:
653+
if self._useMathText or self._usetex:
662654
if sciNotStr != '':
663-
sciNotStr = r'\times%s' % sciNotStr
664-
s = ''.join(('$', sciNotStr, offsetStr, '$'))
655+
sciNotStr = r'\times\mathdefault{%s}' % sciNotStr
656+
s = r'$%s\mathdefault{%s}$' % (sciNotStr, offsetStr)
665657
else:
666658
s = ''.join((sciNotStr, offsetStr))
667659

@@ -784,10 +776,8 @@ def _set_format(self):
784776
break
785777
sigfigs += 1
786778
self.format = '%1.' + str(sigfigs) + 'f'
787-
if self._usetex:
788-
self.format = '$%s$' % self.format
789-
elif self._useMathText:
790-
self.format = '$%s$' % _mathdefault(self.format)
779+
if self._usetex or self._useMathText:
780+
self.format = r'$\mathdefault{%s}$' % self.format
791781

792782
@cbook.deprecated("3.1")
793783
def pprint_val(self, x):
@@ -1079,11 +1069,7 @@ class LogFormatterMathtext(LogFormatter):
10791069

10801070
def _non_decade_format(self, sign_string, base, fx, usetex):
10811071
'Return string for non-decade locations'
1082-
if usetex:
1083-
return (r'$%s%s^{%.2f}$') % (sign_string, base, fx)
1084-
else:
1085-
return ('$%s$' % _mathdefault('%s%s^{%.2f}' %
1086-
(sign_string, base, fx)))
1072+
return r'$\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx)
10871073

10881074
def __call__(self, x, pos=None):
10891075
"""
@@ -1095,10 +1081,7 @@ def __call__(self, x, pos=None):
10951081
min_exp = rcParams['axes.formatter.min_exponent']
10961082

10971083
if x == 0: # Symlog
1098-
if usetex:
1099-
return '$0$'
1100-
else:
1101-
return '$%s$' % _mathdefault('0')
1084+
return r'$\mathdefault{0}$'
11021085

11031086
sign_string = '-' if x < 0 else ''
11041087
x = abs(x)
@@ -1124,17 +1107,11 @@ def __call__(self, x, pos=None):
11241107
base = '%s' % b
11251108

11261109
if abs(fx) < min_exp:
1127-
if usetex:
1128-
return r'${0}{1:g}$'.format(sign_string, x)
1129-
else:
1130-
return '${0}$'.format(_mathdefault(
1131-
'{0}{1:g}'.format(sign_string, x)))
1110+
return r'$\mathdefault{%s%g}$' % (sign_string, x)
11321111
elif not is_x_decade:
11331112
return self._non_decade_format(sign_string, base, fx, usetex)
1134-
elif usetex:
1135-
return r'$%s%s^{%d}$' % (sign_string, base, fx)
11361113
else:
1137-
return '$%s$' % _mathdefault('%s%s^{%d}' % (sign_string, base, fx))
1114+
return r'$\mathdefault{%s%s^{%d}}$' % (sign_string, base, fx)
11381115

11391116

11401117
class LogFormatterSciNotation(LogFormatterMathtext):
@@ -1149,12 +1126,8 @@ def _non_decade_format(self, sign_string, base, fx, usetex):
11491126
coeff = b ** fx / b ** exponent
11501127
if is_close_to_int(coeff):
11511128
coeff = round(coeff)
1152-
if usetex:
1153-
return (r'$%s%g\times%s^{%d}$') % \
1154-
(sign_string, coeff, base, exponent)
1155-
else:
1156-
return ('$%s$' % _mathdefault(r'%s%g\times%s^{%d}' %
1157-
(sign_string, coeff, base, exponent)))
1129+
return r'$\mathdefault{%s%g\times%s^{%d}}$' \
1130+
% (sign_string, coeff, base, exponent)
11581131

11591132

11601133
class LogitFormatter(Formatter):
@@ -1326,8 +1299,6 @@ def __call__(self, x, pos=None):
13261299
return ""
13271300
if x <= 0 or x >= 1:
13281301
return ""
1329-
usetex = rcParams["text.usetex"]
1330-
13311302
if is_close_to_int(2 * x) and round(2 * x) == 1:
13321303
s = self._one_half
13331304
elif x < 0.5 and is_decade(x, rtol=1e-7):
@@ -1342,9 +1313,7 @@ def __call__(self, x, pos=None):
13421313
s = self._one_minus(self._format_value(1-x, 1-self.locs))
13431314
else:
13441315
s = self._format_value(x, self.locs, sci_notation=False)
1345-
if usetex:
1346-
return "$%s$" % s
1347-
return "$%s$" % _mathdefault(s)
1316+
return r"$\mathdefault{%s}$" % s
13481317

13491318
def format_data_short(self, value):
13501319
"""

0 commit comments

Comments
 (0)