|
| 1 | +import functools |
| 2 | +import re |
1 | 3 | import matplotlib.transforms
|
2 | 4 | import numpy as np
|
3 | 5 |
|
@@ -39,3 +41,35 @@ def transform_to_data_coordinates(obj, xdata, ydata):
|
39 | 41 | )
|
40 | 42 | return transform.transform(points).T
|
41 | 43 | return xdata, ydata
|
| 44 | + |
| 45 | + |
| 46 | +_NO_ESCAPE = r"(?<!\\)(?:\\\\)*" |
| 47 | +_split_math = re.compile(_NO_ESCAPE + r"\$").split |
| 48 | +_replace_mathdefault = functools.partial( |
| 49 | + # Replace \mathdefault (when not preceded by an escape) by empty string. |
| 50 | + re.compile(_NO_ESCAPE + r"(\\mathdefault)").sub, "") |
| 51 | + |
| 52 | +def _common_texification(text): |
| 53 | + return _tex_escape(text) |
| 54 | + |
| 55 | +def _tex_escape(text): |
| 56 | + r""" |
| 57 | + Do some necessary and/or useful substitutions for texts to be included in |
| 58 | + LaTeX documents. |
| 59 | + This distinguishes text-mode and math-mode by replacing the math separator |
| 60 | + ``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``) |
| 61 | + are ignored. |
| 62 | + """ |
| 63 | + # Sometimes, matplotlib adds the unknown command \mathdefault. |
| 64 | + # Not using \mathnormal instead since this looks odd for the latex cm font. |
| 65 | + text = _replace_mathdefault(text) |
| 66 | + text = text.replace("\N{MINUS SIGN}", r"\ensuremath{-}") |
| 67 | + # Work around <https://github.com/matplotlib/matplotlib/issues/15493> |
| 68 | + text = text.replace("&", r"\&") |
| 69 | + # split text into normaltext and inline math parts |
| 70 | + parts = _split_math(text) |
| 71 | + for i, s in enumerate(parts): |
| 72 | + if i % 2: # mathmode replacements |
| 73 | + s = r"\(\displaystyle %s\)" % s |
| 74 | + parts[i] = s |
| 75 | + return "".join(parts) |
0 commit comments