Skip to content

Commit d0e91fc

Browse files
author
Gorshanov Vadim
committed
Move function "escape_text" to _text.py
1 parent 6e40267 commit d0e91fc

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

src/tikzplotlib/_line2d.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import datetime
22

33
import numpy as np
4-
import re
54
from matplotlib.dates import num2date
65

76
from . import _color as mycol
87
from . import _files
98
from . import _path as mypath
109
from ._markers import _mpl_marker2pgfp_marker
10+
from ._text import escape_text
1111
from ._util import get_legend_text, has_legend, transform_to_data_coordinates
1212

1313

@@ -101,12 +101,7 @@ def draw_line2d(data, obj):
101101
content += c
102102

103103
if legend_text is not None:
104-
legend_text_escaped = re.sub(r"(\d+(\.\d+)?)\s?%",
105-
r"\\SI{\1}{\\percent}",
106-
legend_text).replace("+-\\SI{",
107-
"\\SI{+-").replace(", s",
108-
", \\SI{\s}")
109-
content.append(f"\\addlegendentry{{{legend_text_escaped}}}\n")
104+
content.append(f"\\addlegendentry{{{escape_text(legend_text)}}}\n")
110105

111106
return data, content
112107

src/tikzplotlib/_text.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,44 @@
11
import matplotlib as mpl
2+
import re
23
from matplotlib.patches import ArrowStyle
34

45
from . import _color
56

7+
def escape_text(text):
8+
"""
9+
Escapes certain patterns in a given text to make them compatible with
10+
LaTeX formatting, especially for SI units.
11+
12+
Parameters:
13+
- text (str): The input string that needs to be processed for LaTeX-
14+
compatible escapes.
15+
16+
Returns:
17+
- str: The text with escaped patterns suitable for LaTeX rendering.
18+
19+
The function primarily performs the following conversions:
20+
1. Converts percentages, e.g., "45%", "45.5 %", to the LaTeX SI
21+
unit format: "\\SI{45}{\\percent}".
22+
2. Fixes potential issues with the "\\SI" unit for the plus-minus
23+
notation.
24+
3. Corrects ", s" patterns to ", \\SI{\\s}".
25+
26+
Note:
27+
This function assumes that the input text is likely to contain numeric
28+
values that need to be presented using SI notation in LaTeX. For
29+
correct rendering, the siunitx LaTeX package should be included in
30+
the document.
31+
32+
Example:
33+
Given the input: "The efficiency is 45% and the tolerance is
34+
+-\\SI{2}{\\degree}, s"
35+
The output will be: "The efficiency is \\SI{45}{\\percent} and
36+
the tolerance is \\SI{+-2}{\\degree}, \\SI{\s}"
37+
"""
38+
return re.sub(r"(\d+(\.\d+)?)\s?%", r"\\SI{\1}{\\percent}",
39+
text).replace("+-\\SI{", "\\SI{+-").replace(", s",
40+
", \\SI{\\s}")
41+
642

743
def draw_text(data, obj):
844
"""Paints text on the graph."""

0 commit comments

Comments
 (0)