-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvas.py
More file actions
1439 lines (1270 loc) · 47.3 KB
/
Copy pathcanvas.py
File metadata and controls
1439 lines (1270 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
from dataclasses import dataclass
from typing import Mapping
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
from plotly.subplots import make_subplots
from tikzfigure import TikzFigure
from maxplotlib.backends.matplotlib.utils import (
set_size,
setup_plotstyle,
setup_tex_fonts,
)
from maxplotlib.backends.plotext import PlotextFigure, create_plotext_figure
from maxplotlib.colors.colors import Color
from maxplotlib.linestyle.linestyle import Linestyle
from maxplotlib.subfigure.line_plot import LinePlot
from maxplotlib.utils.options import Backends
@dataclass(frozen=True)
class SubplotSpacing:
"""Typed spacing configuration for subplot grids."""
wspace: float = 0.08
hspace: float = 0.1
def to_gridspec_kw(self) -> dict[str, float]:
return {"wspace": self.wspace, "hspace": self.hspace}
def _parse_bool_env_var(name: str, default: bool = False) -> bool:
value = os.getenv(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def plot_matplotlib(tikzfigure: TikzFigure, ax, layers=None):
"""
Plot all nodes and paths on the provided axis using Matplotlib.
Parameters:
- ax (matplotlib.axes.Axes): Axis on which to plot the figure.
"""
# TODO: Specify which layers to retreive nodes from with layers=layers
nodes = tikzfigure.layers.get_nodes()
paths = tikzfigure.layers.get_paths()
for path in paths:
x_coords = [node.x for node in path.nodes]
y_coords = [node.y for node in path.nodes]
# Parse path color
path_color_spec = path.kwargs.get("color", "black")
try:
color = Color(path_color_spec).to_rgb()
except ValueError as e:
print(e)
color = "black"
# Parse line width
line_width_spec = path.kwargs.get("line_width", 1)
if isinstance(line_width_spec, str):
match = re.match(r"([\d.]+)(pt)?", line_width_spec)
if match:
line_width = float(match.group(1))
else:
print(
f"Invalid line width specification: '{line_width_spec}', defaulting to 1",
)
line_width = 1
else:
line_width = float(line_width_spec)
# Parse line style using Linestyle class
style_spec = path.kwargs.get("style", "solid")
linestyle = Linestyle(style_spec).to_matplotlib()
ax.plot(
x_coords,
y_coords,
color=color,
linewidth=line_width,
linestyle=linestyle,
zorder=1, # Lower z-order to place behind nodes
)
# Plot nodes after paths so they appear on top
for node in nodes:
# Determine shape and size
shape = node.kwargs.get("shape", "circle")
fill_color_spec = node.kwargs.get("fill", "white")
edge_color_spec = node.kwargs.get("draw", "black")
linewidth = float(node.kwargs.get("line_width", 1))
size = float(node.kwargs.get("size", 1))
# Parse colors using the Color class
try:
facecolor = Color(fill_color_spec).to_rgb()
except ValueError as e:
print(e)
facecolor = "white"
try:
edgecolor = Color(edge_color_spec).to_rgb()
except ValueError as e:
print(e)
edgecolor = "black"
# Plot shapes
if shape == "circle":
radius = size / 2
circle = patches.Circle(
(node.x, node.y),
radius,
facecolor=facecolor,
edgecolor=edgecolor,
linewidth=linewidth,
zorder=2, # Higher z-order to place on top of paths
)
ax.add_patch(circle)
elif shape == "rectangle":
width = height = size
rect = patches.Rectangle(
(node.x - width / 2, node.y - height / 2),
width,
height,
facecolor=facecolor,
edgecolor=edgecolor,
linewidth=linewidth,
zorder=2, # Higher z-order
)
ax.add_patch(rect)
else:
# Default to circle if shape is unknown
radius = size / 2
circle = patches.Circle(
(node.x, node.y),
radius,
facecolor=facecolor,
edgecolor=edgecolor,
linewidth=linewidth,
zorder=2,
)
ax.add_patch(circle)
# Add text inside the shape
if node.content:
ax.text(
node.x,
node.y,
node.content,
fontsize=self._fontsize,
ha="center",
va="center",
wrap=True,
zorder=3, # Even higher z-order for text
)
# Remove axes, ticks, and legend
ax.axis("off")
# Adjust plot limits
all_x = [node.x for node in nodes]
all_y = [node.y for node in nodes]
padding = 1 # Adjust padding as needed
ax.set_xlim(min(all_x) - padding, max(all_x) + padding)
ax.set_ylim(min(all_y) - padding, max(all_y) + padding)
ax.set_aspect("equal", adjustable="datalim")
class Canvas:
def __init__(
self,
nrows: int = 1,
ncols: int = 1,
figsize: tuple | None = None,
caption: str | None = None,
description: str | None = None,
label: str | None = None,
fontsize: int = 10,
dpi: int | None = None,
width: str | None = None,
ratio: str = "golden", # TODO Add literal
usetex: bool | None = None,
subplot_spacing: SubplotSpacing | None = None,
gridspec_kw: Mapping[str, float] | None = None,
):
"""
Initialize the Canvas class for multiple subplots.
Parameters:
nrows (int): Number of subplot rows. Default is 1.
ncols (int): Number of subplot columns. Default is 1.
figsize (tuple): Figure size.
caption (str): Caption for the figure.
description (str): Description for the figure.
label (str): Label for the figure.
fontsize (int): Font size. Default is 10.
dpi (int | None): Optional export/render DPI override.
width (str | None): Optional figure width, e.g. "7cm".
ratio (str): Aspect ratio. Default is "golden".
usetex (bool | None): Default text.usetex behavior for this canvas.
If None, read from MAXPLOTLIB_USETEX environment variable.
subplot_spacing (SubplotSpacing): Typed subplot spacing.
Default is SubplotSpacing(wspace=0.08, hspace=0.1).
gridspec_kw (Mapping[str, float]): Optional matplotlib gridspec kwargs.
Kept for compatibility with existing code.
"""
self._nrows = nrows
self._ncols = ncols
self._figsize = figsize
self._caption = caption
self._description = description
self._label = label
self._fontsize = fontsize
self._dpi = dpi
self._width = width
self._ratio = ratio
self._usetex = (
_parse_bool_env_var("MAXPLOTLIB_USETEX", default=False)
if usetex is None
else usetex
)
if subplot_spacing is not None and gridspec_kw is not None:
raise ValueError("Pass either subplot_spacing or gridspec_kw, not both.")
if subplot_spacing is None and gridspec_kw is None:
subplot_spacing = SubplotSpacing()
if subplot_spacing is not None:
self._gridspec_kw = subplot_spacing.to_gridspec_kw()
else:
self._gridspec_kw = dict(gridspec_kw)
self._plotted = False
self._matplotlib_fig = None
self._matplotlib_axes = None
self._plotext_figure = None
self._suptitle: str | None = None
self._suptitle_kwargs: dict = {}
# Dictionary to store lines for each subplot
# Key: (row, col), Value: list of lines with their data and kwargs
self._subplots = {}
self._num_subplots = 0
self._subplot_matrix = [[None] * self.ncols for _ in range(self.nrows)]
# ------------------------------------------------------------------
# Factory
# ------------------------------------------------------------------
@classmethod
def subplots(
cls,
nrows: int = 1,
ncols: int = 1,
squeeze: bool = True,
wspace: float | None = None,
hspace: float | None = None,
**canvas_kwargs,
):
"""
Create a Canvas pre-filled with LinePlot subplots, mirroring
``matplotlib.pyplot.subplots()``.
Parameters:
nrows, ncols (int): Grid dimensions.
squeeze (bool): If True, return a single subplot instead of a 1-element
list when the grid is 1×1 or when one dimension is 1.
wspace, hspace (float): Convenience subplot spacing arguments.
These map to matplotlib gridspec spacing values.
**canvas_kwargs: Forwarded to the Canvas constructor.
Returns:
(canvas, axes): A tuple of the Canvas and either a single LinePlot,
a flat list (when one dimension is 1 and squeeze=True), or a
2-D list of LinePlots.
Examples:
>>> canvas, ax = Canvas.subplots()
>>> canvas, (ax1, ax2) = Canvas.subplots(ncols=2)
>>> canvas, axes = Canvas.subplots(nrows=2, ncols=2) # axes[row][col]
"""
spacing_given = wspace is not None or hspace is not None
if spacing_given and (
"subplot_spacing" in canvas_kwargs or "gridspec_kw" in canvas_kwargs
):
raise ValueError(
"Use either wspace/hspace or subplot_spacing/gridspec_kw, not both."
)
if spacing_given:
canvas_kwargs["subplot_spacing"] = SubplotSpacing(
wspace=0.08 if wspace is None else wspace,
hspace=0.1 if hspace is None else hspace,
)
canvas = cls(nrows=nrows, ncols=ncols, **canvas_kwargs)
axes = [
[canvas.add_subplot(row=r, col=c) for c in range(ncols)]
for r in range(nrows)
]
if squeeze:
if nrows == 1 and ncols == 1:
return canvas, axes[0][0]
if nrows == 1:
return canvas, axes[0]
if ncols == 1:
return canvas, [row[0] for row in axes]
return canvas, axes
@property
def _subplot_dict(self):
return self._subplots
@property
def layers(self):
layers = []
for (row, col), subplot in self._subplot_dict.items():
layers.extend(subplot.layers)
return list(set(layers))
def generate_new_rowcol(self, row, col):
if row is None:
for irow in range(self.nrows):
has_none = any(item is None for item in self._subplot_matrix[irow])
if has_none:
row = irow
break
assert row is not None, "Not enough rows!"
if col is None:
for icol in range(self.ncols):
if self._subplot_matrix[row][icol] is None:
col = icol
break
assert col is not None, "Not enough columns!"
return row, col
def add_line(
self,
x,
y,
layer=0,
subplot: LinePlot | None = None,
row: int | None = None,
col: int | None = None,
**kwargs,
):
if row is not None and col is not None:
try:
subplot = self._subplot_matrix[row][col]
except KeyError:
raise ValueError("Invalid subplot position.")
else:
row, col = 0, 0
subplot = self._subplot_matrix[row][col]
if subplot is None:
row, col = self.generate_new_rowcol(row, col)
subplot = self.add_subplot(col=col, row=row)
subplot.add_line(
x=x,
y=y,
layer=layer,
**kwargs,
)
def _get_or_create_subplot(self, row, col):
"""Return the subplot at (row, col), creating it if needed."""
if row is not None and col is not None:
try:
sp = self._subplot_matrix[row][col]
except (IndexError, KeyError):
raise ValueError("Invalid subplot position.")
else:
row, col = 0, 0
sp = self._subplot_matrix[row][col]
if sp is None:
row, col = self.generate_new_rowcol(row, col)
sp = self.add_subplot(col=col, row=row)
return sp
def scatter(
self,
x,
y,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""
Add a scatter plot to the canvas (matplotlib-style convenience method).
Parameters:
x (array-like): X-axis data.
y (array-like): Y-axis data.
layer (int): Layer index (default 0).
row, col (int): Subplot position (default top-left).
**kwargs: Forwarded to the backend (e.g., color, marker, s, label).
"""
sp = self._get_or_create_subplot(row, col)
sp.scatter(x, y, layer=layer, **kwargs)
def bar(
self,
x,
height,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""
Add a bar chart to the canvas (matplotlib-style convenience method).
Parameters:
x (array-like): X positions of the bars.
height (array-like): Heights of the bars.
layer (int): Layer index (default 0).
row, col (int): Subplot position (default top-left).
**kwargs: Forwarded to the backend (e.g., color, width, label).
"""
sp = self._get_or_create_subplot(row, col)
sp.bar(x, height, layer=layer, **kwargs)
def set_xlabel(self, label: str, row: int | None = None, col: int | None = None):
"""Set the x-axis label for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_xlabel(label)
def set_ylabel(self, label: str, row: int | None = None, col: int | None = None):
"""Set the y-axis label for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_ylabel(label)
def set_title(self, title: str, row: int | None = None, col: int | None = None):
"""Set the title for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_title(title)
def set_xlim(
self, left=None, right=None, row: int | None = None, col: int | None = None
):
"""Set the x-axis limits for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_xlim(left, right)
def set_ylim(
self, bottom=None, top=None, row: int | None = None, col: int | None = None
):
"""Set the y-axis limits for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_ylim(bottom, top)
def set_grid(
self, visible: bool = True, row: int | None = None, col: int | None = None
):
"""Show or hide the grid for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_grid(visible)
def set_legend(
self, visible: bool = True, row: int | None = None, col: int | None = None
):
"""Show or hide the legend for a subplot (default top-left)."""
self._get_or_create_subplot(row, col).set_legend(visible)
def set_xscale(self, scale: str, row: int | None = None, col: int | None = None):
"""Set x-axis scale ('linear', 'log', 'symlog') for a subplot."""
self._get_or_create_subplot(row, col).set_xscale(scale)
def set_yscale(self, scale: str, row: int | None = None, col: int | None = None):
"""Set y-axis scale ('linear', 'log', 'symlog') for a subplot."""
self._get_or_create_subplot(row, col).set_yscale(scale)
def set_xticks(
self, ticks, labels=None, row: int | None = None, col: int | None = None
):
"""Set x-axis tick positions (and optional labels) for a subplot."""
self._get_or_create_subplot(row, col).set_xticks(ticks, labels)
def set_yticks(
self, ticks, labels=None, row: int | None = None, col: int | None = None
):
"""Set y-axis tick positions (and optional labels) for a subplot."""
self._get_or_create_subplot(row, col).set_yticks(ticks, labels)
def fill_between(
self,
x,
y1,
y2=0,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Fill the region between two curves on a subplot."""
self._get_or_create_subplot(row, col).fill_between(
x, y1, y2, layer=layer, **kwargs
)
def errorbar(
self,
x,
y,
yerr=None,
xerr=None,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add an error-bar line to a subplot."""
self._get_or_create_subplot(row, col).errorbar(
x, y, yerr=yerr, xerr=xerr, layer=layer, **kwargs
)
def axhline(
self, y=0, layer=0, row: int | None = None, col: int | None = None, **kwargs
):
"""Add a full-width horizontal reference line to a subplot."""
self._get_or_create_subplot(row, col).axhline(y=y, layer=layer, **kwargs)
def axvline(
self, x=0, layer=0, row: int | None = None, col: int | None = None, **kwargs
):
"""Add a full-height vertical reference line to a subplot."""
self._get_or_create_subplot(row, col).axvline(x=x, layer=layer, **kwargs)
def hlines(
self,
y,
xmin,
xmax,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add horizontal lines at specified y positions to a subplot."""
self._get_or_create_subplot(row, col).hlines(
y, xmin, xmax, layer=layer, **kwargs
)
def vlines(
self,
x,
ymin,
ymax,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add vertical lines at specified x positions to a subplot."""
self._get_or_create_subplot(row, col).vlines(
x, ymin, ymax, layer=layer, **kwargs
)
def annotate(
self,
text,
xy,
xytext=None,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add an annotation (with optional arrow) to a subplot."""
self._get_or_create_subplot(row, col).annotate(
text, xy, xytext=xytext, layer=layer, **kwargs
)
def text(
self, x, y, s, layer=0, row: int | None = None, col: int | None = None, **kwargs
):
"""Add a text label at (x, y) on a subplot."""
self._get_or_create_subplot(row, col).text(x, y, s, layer=layer, **kwargs)
def imshow(
self,
data,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add an image/matrix plot to a subplot."""
self._get_or_create_subplot(row, col).add_imshow(data, layer=layer, **kwargs)
def add_patch(
self,
patch,
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add a Matplotlib patch to a subplot."""
self._get_or_create_subplot(row, col).add_patch(patch, layer=layer, **kwargs)
def colorbar(
self,
label: str = "",
layer=0,
row: int | None = None,
col: int | None = None,
**kwargs,
):
"""Add a colorbar to the most recent imshow() on a subplot (matplotlib backend)."""
self._get_or_create_subplot(row, col).add_colorbar(
label=label, layer=layer, **kwargs
)
# ------------------------------------------------------------------
# Multi-subplot helpers
# ------------------------------------------------------------------
def subplot(self, row: int = 0, col: int = 0) -> LinePlot:
"""
Return the LinePlot at position (row, col).
Raises ValueError if no subplot has been created there yet.
"""
sp = self._subplot_matrix[row][col]
if sp is None:
raise ValueError(
f"No subplot at ({row}, {col}). "
"Call add_subplot() or use Canvas.subplots() first."
)
return sp
def iter_subplots(self):
"""Yield (row, col, subplot) for every initialized subplot, row-major."""
for r in range(self.nrows):
for c in range(self.ncols):
sp = self._subplot_matrix[r][c]
if sp is not None:
yield r, c, sp
def suptitle(self, title: str, **kwargs):
"""
Set a figure-level title (rendered above all subplots).
Parameters:
title (str): Title text.
**kwargs: Forwarded to matplotlib's fig.suptitle (e.g., fontsize, y).
"""
self._suptitle = title
self._suptitle_kwargs = kwargs
def add_tikzfigure(
self,
col=None,
row=None,
label=None,
**kwargs,
):
"""
Adds a subplot to the figure.
Parameters:
**kwargs: Arbitrary keyword arguments.
"""
row, col = self.generate_new_rowcol(row, col)
# Initialize the LinePlot for the given subplot position
tikz_figure = TikzFigure(
label=label,
**kwargs,
)
self._subplot_matrix[row][col] = tikz_figure
# Store the LinePlot instance by its position for easy access
if label is None:
self._subplots[(row, col)] = tikz_figure
else:
self._subplots[label] = tikz_figure
return tikz_figure
def add_subplot(
self,
col: int | None = None,
row: int | None = None,
figsize: tuple = (10, 6),
title: str | None = None,
caption: str | None = None,
description: str | None = None,
label: str | None = None,
grid: bool = False,
legend: bool = False,
xmin: float | int | None = None,
xmax: float | int | None = None,
ymin: float | int | None = None,
ymax: float | int | None = None,
xlabel: str | None = None,
ylabel: str | None = None,
xscale: float | int = 1.0,
yscale: float | int = 1.0,
xshift: float | int = 0.0,
yshift: float | int = 0.0,
):
"""
Adds a subplot to the figure.
Parameters:
**kwargs: Arbitrary keyword arguments.
- col (int): Column index for the subplot.
- row (int): Row index for the subplot.
- label (str): Label to identify the subplot.
"""
row, col = self.generate_new_rowcol(row, col)
# Initialize the LinePlot for the given subplot position
line_plot = LinePlot(
title=title,
grid=grid,
legend=legend,
xmin=xmin,
xmax=xmax,
ymin=ymin,
ymax=ymax,
xlabel=xlabel,
ylabel=ylabel,
xscale=xscale,
yscale=yscale,
xshift=xshift,
yshift=yshift,
)
self._subplot_matrix[row][col] = line_plot
# Store the LinePlot instance by its position for easy access
if label is None:
self._subplots[(row, col)] = line_plot
else:
self._subplots[label] = line_plot
return line_plot
def savefig(
self,
filename,
backend: Backends = "matplotlib",
layers: list | None = None,
layer_by_layer: bool = False,
verbose: bool = False,
):
filename_no_extension, extension = os.path.splitext(filename)
if backend == "matplotlib":
if layer_by_layer:
layers = []
for layer in self.layers:
layers.append(layer)
fig, axs = self.plot(
show=False,
backend="matplotlib",
savefig=True,
layers=layers,
)
_fn = f"{filename_no_extension}_{layers}.{extension}"
savefig_kwargs = {"dpi": self.dpi} if self.dpi is not None else {}
fig.savefig(_fn, **savefig_kwargs)
print(f"Saved {_fn}")
else:
if layers is None:
layers = self.layers
full_filepath = filename
else:
full_filepath = f"{filename_no_extension}_{layers}.{extension}"
if self._plotted:
savefig_kwargs = {"dpi": self.dpi} if self.dpi is not None else {}
self._matplotlib_fig.savefig(full_filepath, **savefig_kwargs)
else:
fig, axs = self.plot(
backend="matplotlib",
savefig=True,
layers=layers,
)
savefig_kwargs = {"dpi": self.dpi} if self.dpi is not None else {}
fig.savefig(full_filepath, **savefig_kwargs)
if verbose:
print(f"Saved {full_filepath}")
elif backend == "plotext":
if layer_by_layer:
layers = []
for layer in self.layers:
layers.append(layer)
figure = self.plot(
backend="plotext",
savefig=False,
layers=layers,
)
_fn = f"{filename_no_extension}_{layers}.{extension}"
figure.savefig(_fn)
print(f"Saved {_fn}")
else:
if layers is None:
layers = self.layers
full_filepath = filename
else:
full_filepath = f"{filename_no_extension}_{layers}.{extension}"
figure = self.plot(
backend="plotext",
savefig=False,
layers=layers,
)
figure.savefig(full_filepath)
if verbose:
print(f"Saved {full_filepath}")
elif backend == "plotly":
if layer_by_layer:
layers = []
for layer in self.layers:
layers.append(layer)
full_filepath = f"{filename_no_extension}_{layers}{extension}"
fig = self.plot(
backend="plotly",
savefig=False,
layers=layers,
)
self._save_plotly(fig, full_filepath)
if verbose:
print(f"Saved {full_filepath}")
else:
if layers is None:
layers = self.layers
full_filepath = filename
else:
full_filepath = f"{filename_no_extension}_{layers}{extension}"
fig = self.plot(
backend="plotly",
savefig=False,
layers=layers,
)
self._save_plotly(fig, full_filepath)
if verbose:
print(f"Saved {full_filepath}")
def plot(
self,
backend: Backends = "matplotlib",
savefig: bool = False,
layers: list | None = None,
usetex: bool | None = None,
verbose: bool = False,
):
resolved_usetex = self._usetex if usetex is None else usetex
if verbose:
print(f"Plotting figure using backend: {backend}")
if backend == "matplotlib":
return self.plot_matplotlib(
savefig=savefig,
layers=layers,
usetex=resolved_usetex,
verbose=verbose,
)
elif backend == "plotly":
return self.plot_plotly(
savefig=savefig,
layers=layers,
usetex=resolved_usetex,
verbose=verbose,
)
elif backend == "plotext":
return self.plot_plotext(
savefig=savefig,
layers=layers,
verbose=verbose,
)
elif backend == "tikzfigure":
return self.plot_tikzfigure(savefig=savefig, verbose=verbose)
else:
raise ValueError(f"Invalid backend: {backend}")
def show(
self,
backend: Backends = "matplotlib",
layers: list | None = None,
usetex: bool | None = None,
verbose: bool = False,
):
if verbose:
print(f"Showing canvas using backend: {backend}")
if backend == "matplotlib":
if verbose:
print("Generating Matplotlib figure for display...")
fig, axes = self.plot(
backend="matplotlib",
savefig=False,
layers=layers,
usetex=usetex,
verbose=verbose,
)
if verbose:
print("Displaying Matplotlib figure...")
plt.show()
return fig, axes
elif backend == "plotly":
resolved_usetex = self._usetex if usetex is None else usetex
fig = self.plot_plotly(
savefig=False, layers=layers, usetex=resolved_usetex, verbose=verbose
)
fig.show()
return fig
elif backend == "plotext":
figure = self.plot_plotext(
savefig=False,
layers=layers,
verbose=verbose,
)
figure.show()
return figure
elif backend == "tikzfigure":
fig = self.plot_tikzfigure(savefig=False, verbose=verbose)
# TikzFigure handles all rendering (single or multi-subplot)
fig.show(transparent=False)
return fig
else:
raise ValueError("Invalid backend")
def plot_matplotlib(
self,
savefig: bool = False,
layers: list | None = None,
usetex: bool | None = None,
verbose: bool = False,
):
"""
Generate and optionally display the subplots.
Parameters:
filename (str, optional): Filename to save the figure.
"""
if verbose:
print("Generating Matplotlib figure...")
resolved_usetex = self._usetex if usetex is None else usetex
tex_fonts = setup_tex_fonts(fontsize=self.fontsize, usetex=resolved_usetex)
render_dpi = self.dpi if savefig else None
setup_plotstyle(
tex_fonts=tex_fonts,
axes_grid=True,
axes_grid_which="major",
grid_alpha=1.0,
grid_linestyle="dotted",
)
if verbose:
print("Plot style set up.")
print(f"{self._figsize = } {self._width = } {self._ratio = }")
subplot_kwargs = {
"squeeze": False,
"gridspec_kw": self._gridspec_kw,
}
if self._figsize is not None:
subplot_kwargs["figsize"] = self._figsize
elif self._width is not None:
fig_width, fig_height = set_size(
width=self._width,
ratio=self._ratio,
dpi=render_dpi,
verbose=verbose,
)
subplot_kwargs["figsize"] = (fig_width, fig_height)
if verbose:
if "figsize" in subplot_kwargs:
fig_width, fig_height = subplot_kwargs["figsize"]
print(f"Figure size: {fig_width} x {fig_height} inches")
else:
print("Figure size: Matplotlib default")
print(f"Render DPI override: {render_dpi} (export DPI: {self.dpi})")
if render_dpi is not None:
subplot_kwargs["dpi"] = render_dpi
fig, axes = plt.subplots(
self.nrows,
self.ncols,
**subplot_kwargs,
)
if verbose:
print(f"Created Matplotlib figure and axes with shape {axes.shape}")
for (row, col), subplot in self._subplot_dict.items():
ax = axes[row][col]
if isinstance(subplot, TikzFigure):
plot_matplotlib(subplot, ax, layers=layers)
else:
subplot.plot_matplotlib(ax, layers=layers)
# ax.set_title(f"Subplot ({row}, {col})")
ax.grid()