Skip to content

Commit 23ac8a7

Browse files
committed
Allow for setting MAXPLOTLIB_USETEX environment variable or a parameter for Canvas
1 parent 4b608f2 commit 23ac8a7

2 files changed

Lines changed: 78 additions & 8 deletions

File tree

src/maxplotlib/canvas/canvas.py

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ def to_gridspec_kw(self) -> dict[str, float]:
3131
return {"wspace": self.wspace, "hspace": self.hspace}
3232

3333

34+
def _parse_bool_env_var(name: str, default: bool = False) -> bool:
35+
value = os.getenv(name)
36+
if value is None:
37+
return default
38+
return value.strip().lower() in {"1", "true", "yes", "on"}
39+
40+
3441
def plot_matplotlib(tikzfigure: TikzFigure, ax, layers=None):
3542
"""
3643
Plot all nodes and paths on the provided axis using Matplotlib.
@@ -179,6 +186,7 @@ def __init__(
179186
dpi: int = 300,
180187
width: str = "5cm",
181188
ratio: str = "golden", # TODO Add literal
189+
usetex: bool | None = None,
182190
subplot_spacing: SubplotSpacing | None = None,
183191
gridspec_kw: Mapping[str, float] | None = None,
184192
):
@@ -196,6 +204,8 @@ def __init__(
196204
dpi (int): DPI for the figure. Default is 300.
197205
width (str): Width of the figure. Default is "17cm".
198206
ratio (str): Aspect ratio. Default is "golden".
207+
usetex (bool | None): Default text.usetex behavior for this canvas.
208+
If None, read from MAXPLOTLIB_USETEX environment variable.
199209
subplot_spacing (SubplotSpacing): Typed subplot spacing.
200210
Default is SubplotSpacing(wspace=0.08, hspace=0.1).
201211
gridspec_kw (Mapping[str, float]): Optional matplotlib gridspec kwargs.
@@ -212,6 +222,11 @@ def __init__(
212222
self._dpi = dpi
213223
self._width = width
214224
self._ratio = ratio
225+
self._usetex = (
226+
_parse_bool_env_var("MAXPLOTLIB_USETEX", default=False)
227+
if usetex is None
228+
else usetex
229+
)
215230
if subplot_spacing is not None and gridspec_kw is not None:
216231
raise ValueError("Pass either subplot_spacing or gridspec_kw, not both.")
217232
if subplot_spacing is None and gridspec_kw is None:
@@ -764,23 +779,25 @@ def plot(
764779
backend: Backends = "matplotlib",
765780
savefig=False,
766781
layers=None,
767-
usetex: bool = False,
782+
usetex: bool | None = None,
768783
verbose: bool = False,
769784
):
785+
resolved_usetex = self._usetex if usetex is None else usetex
786+
770787
if verbose:
771788
print(f"Plotting figure using backend: {backend}")
772789

773790
if backend == "matplotlib":
774791
return self.plot_matplotlib(
775792
savefig=savefig,
776793
layers=layers,
777-
usetex=usetex,
794+
usetex=resolved_usetex,
778795
verbose=verbose,
779796
)
780797
elif backend == "plotly":
781798
return self.plot_plotly(
782799
savefig=savefig,
783-
usetex=usetex,
800+
usetex=resolved_usetex,
784801
verbose=verbose,
785802
)
786803
elif backend == "plotext":
@@ -798,6 +815,7 @@ def show(
798815
self,
799816
backend: Backends = "matplotlib",
800817
layers: list | None = None,
818+
usetex: bool | None = None,
801819
verbose: bool = False,
802820
):
803821
if verbose:
@@ -808,11 +826,13 @@ def show(
808826
backend="matplotlib",
809827
savefig=False,
810828
layers=layers,
829+
usetex=usetex,
811830
verbose=verbose,
812831
)
813832
# self._matplotlib_fig.show()
814833
elif backend == "plotly":
815-
self.plot_plotly(savefig=False)
834+
resolved_usetex = self._usetex if usetex is None else usetex
835+
self.plot_plotly(savefig=False, usetex=resolved_usetex)
816836
elif backend == "plotext":
817837
figure = self.plot_plotext(
818838
savefig=False,
@@ -833,7 +853,7 @@ def plot_matplotlib(
833853
self,
834854
savefig: bool = False,
835855
layers: list | None = None,
836-
usetex: bool = False,
856+
usetex: bool | None = None,
837857
verbose: bool = False,
838858
):
839859
"""
@@ -845,7 +865,8 @@ def plot_matplotlib(
845865
if verbose:
846866
print("Generating Matplotlib figure...")
847867

848-
tex_fonts = setup_tex_fonts(fontsize=self.fontsize, usetex=usetex)
868+
resolved_usetex = self._usetex if usetex is None else usetex
869+
tex_fonts = setup_tex_fonts(fontsize=self.fontsize, usetex=resolved_usetex)
849870

850871
setup_plotstyle(
851872
tex_fonts=tex_fonts,
@@ -1009,7 +1030,7 @@ def plot_plotext(
10091030
self._plotext_figure = wrapped
10101031
return wrapped
10111032

1012-
def plot_plotly(self, show=True, savefig=None, usetex=False):
1033+
def plot_plotly(self, show=True, savefig=None, usetex: bool | None = None):
10131034
"""
10141035
Generate and optionally display the subplots using Plotly.
10151036
@@ -1018,9 +1039,11 @@ def plot_plotly(self, show=True, savefig=None, usetex=False):
10181039
savefig (str, optional): Filename to save the figure if provided.
10191040
"""
10201041

1042+
resolved_usetex = self._usetex if usetex is None else usetex
1043+
10211044
setup_tex_fonts(
10221045
fontsize=self.fontsize,
1023-
usetex=usetex,
1046+
usetex=resolved_usetex,
10241047
) # adjust or redefine for Plotly if needed
10251048

10261049
# Set default width and height if not specified
@@ -1112,6 +1135,10 @@ def label(self):
11121135
def figsize(self):
11131136
return self._figsize
11141137

1138+
@property
1139+
def usetex(self):
1140+
return self._usetex
1141+
11151142
@property
11161143
def subplot_matrix(self):
11171144
return self._subplot_matrix

src/maxplotlib/tests/test_canvas.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,5 +270,48 @@ def test_canvas_subplots_spacing_args_and_explicit_spacing_are_mutually_exclusiv
270270
)
271271

272272

273+
def test_canvas_usetex_reads_environment_default(monkeypatch):
274+
from maxplotlib import Canvas
275+
276+
monkeypatch.setenv("MAXPLOTLIB_USETEX", "true")
277+
canvas = Canvas()
278+
assert canvas.usetex is True
279+
280+
281+
def test_canvas_usetex_constructor_overrides_environment(monkeypatch):
282+
from maxplotlib import Canvas
283+
284+
monkeypatch.setenv("MAXPLOTLIB_USETEX", "true")
285+
canvas = Canvas(usetex=False)
286+
assert canvas.usetex is False
287+
288+
289+
def test_canvas_plot_usetex_precedence(monkeypatch):
290+
import matplotlib.pyplot as plt
291+
292+
from maxplotlib import Canvas
293+
import maxplotlib.canvas.canvas as canvas_module
294+
295+
captured: list[bool] = []
296+
297+
def fake_setup_tex_fonts(fontsize=14, usetex=False):
298+
captured.append(usetex)
299+
return {}
300+
301+
monkeypatch.setattr(canvas_module, "setup_tex_fonts", fake_setup_tex_fonts)
302+
303+
canvas = Canvas(usetex=True)
304+
subplot = canvas.add_subplot()
305+
subplot.plot([0, 1], [0, 1])
306+
307+
fig, _ = canvas.plot_matplotlib()
308+
plt.close(fig)
309+
310+
fig, _ = canvas.plot_matplotlib(usetex=False)
311+
plt.close(fig)
312+
313+
assert captured == [True, False]
314+
315+
273316
if __name__ == "__main__":
274317
test()

0 commit comments

Comments
 (0)