gleplot 6.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gleplot/__init__.py ADDED
@@ -0,0 +1,772 @@
1
+ """
2
+ gleplot - write standard GLE from Python, with matplotlib-shaped names
3
+
4
+ A Python library that writes GLE (Graphics Layout Engine) scripts for
5
+ publication-quality vector graphics, through matplotlib-shaped calls.
6
+
7
+ Features
8
+ --------
9
+ - Matplotlib-compatible API (plot, scatter, bar, fill_between, errorbar)
10
+ - Text annotations and arrows in data coordinates or axes fractions (text,
11
+ annotate)
12
+ - Subplots with flexible grid layouts (subplots, add_subplot)
13
+ - Native vector graphics output (PDF, PNG, EPS)
14
+ - Inline display in Jupyter notebooks (view)
15
+ - Support for line styles, markers, and colors
16
+ - Error bars (symmetric, asymmetric, horizontal)
17
+ - Logarithmic scales
18
+ - Legend and axis labels
19
+ - Semantic per-series data file naming (data_name) and figure-level prefixes (data_prefix)
20
+ - Direct GLE script generation
21
+
22
+ Usage
23
+ -----
24
+ import gleplot as glp
25
+
26
+ fig = glp.figure(figsize=(8, 6))
27
+ ax = fig.add_subplot(111)
28
+
29
+ ax.plot([1, 2, 3], [1, 4, 9], 'b-', label='quadratic')
30
+ ax.scatter([1, 2, 3], [1, 2, 3], color='red', label='points')
31
+
32
+ ax.set_xlabel('X axis')
33
+ ax.set_ylabel('Y axis')
34
+ ax.set_title('Example Plot')
35
+ ax.legend()
36
+
37
+ fig.savefig('output.pdf') # Saves as PDF
38
+ fig.savefig('output.gle') # Saves as GLE script only
39
+ fig.view() # Display inline in Jupyter notebook
40
+
41
+ Classes
42
+ -------
43
+ Figure
44
+ Matplotlib-like figure container
45
+ Axes
46
+ Matplotlib-like axes for plotting
47
+
48
+ Functions
49
+ ---------
50
+ figure(figsize=(8, 6), dpi=100)
51
+ Create a new figure
52
+ """
53
+
54
+ __version__ = "6.0.0"
55
+ __author__ = "gleplot contributors"
56
+
57
+ from typing import Union
58
+
59
+ import numpy as np
60
+
61
+ from . import _warn
62
+ from .axes import Axes, validate_tick_format
63
+ from .colors import get_color_palette, rgb_to_gle
64
+ from .compiler import GLECompiler
65
+ from .config import (
66
+ GLEGraphConfig,
67
+ GLEMarkerConfig,
68
+ GLEStyleConfig,
69
+ GlobalConfig,
70
+ )
71
+ from .figure import Figure
72
+ from .markers import get_gle_marker
73
+ from .mathtext import mathtext_to_gle
74
+
75
+ # Series data sources: where a series' numbers come from. The scripting API
76
+ # always produces InlineData (baked arrays) and never needs these; they are
77
+ # the API an embedding application uses to point series at its own tables.
78
+ from .sources import (
79
+ ColumnRef,
80
+ DanglingSourceRef,
81
+ DanglingSourceWarning,
82
+ DataProvider,
83
+ DataSource,
84
+ DictDataProvider,
85
+ GridRef,
86
+ InlineData,
87
+ TableData,
88
+ )
89
+
90
+ # Module-level convenience functions (for matplotlib compatibility)
91
+
92
+ _current_figure = None
93
+
94
+
95
+ def open_gle(path, *, base_dir=None) -> Figure:
96
+ """Open a ``.gle`` file (or GLE source text) as a gleplot :class:`Figure`.
97
+
98
+ Convenience wrapper around
99
+ :func:`gleplot.parser.recognizer.parse_gle_figure` that returns just the
100
+ reconstructed figure. Each recovery note (something kept as raw GLE,
101
+ guessed, or converted) is raised as a ``UserWarning`` whose text is
102
+ ``"category: message"``. Use ``parse_gle_figure`` directly to get the
103
+ notes as data instead.
104
+
105
+ Parameters
106
+ ----------
107
+ path : str or pathlib.Path
108
+ Path to a ``.gle`` file, or raw GLE source text.
109
+ base_dir : str or pathlib.Path, optional
110
+ Directory for resolving relative ``data`` references when ``path`` is
111
+ raw source text.
112
+
113
+ Returns
114
+ -------
115
+ Figure
116
+
117
+ Warns
118
+ -----
119
+ UserWarning
120
+ One per recovery note. Python's default warning filter shows a
121
+ message it has already shown from the same line only once; use
122
+ ``parse_gle_figure`` for the full list and each note's line span.
123
+ """
124
+ from .parser.recognizer import parse_gle_figure
125
+
126
+ result = parse_gle_figure(path, base_dir=base_dir)
127
+ for warning in result.warnings:
128
+ _warn.warn_external(warning)
129
+ return result.figure
130
+
131
+
132
+ def figure(
133
+ figsize=(8, 6),
134
+ dpi=100,
135
+ style=None,
136
+ graph=None,
137
+ marker=None,
138
+ data_prefix=None,
139
+ height_ratios=None,
140
+ width_ratios=None,
141
+ **kwargs,
142
+ ) -> Figure:
143
+ """
144
+ Create a new figure.
145
+
146
+ Parameters
147
+ ----------
148
+ figsize : tuple, optional
149
+ Figure size (width, height) in inches. Default: (8, 6)
150
+ dpi : int, optional
151
+ Dots per inch. Default: 100
152
+ style : GLEStyleConfig, optional
153
+ Style configuration. If None, uses global default.
154
+ graph : GLEGraphConfig, optional
155
+ Graph configuration. If None, uses global default.
156
+ marker : GLEMarkerConfig, optional
157
+ Marker configuration. If None, uses global default.
158
+ data_prefix : str, optional
159
+ Custom prefix for data file names (e.g., 'test9' creates 'test9_0.dat', 'test9_1.dat').
160
+ If None, uses global counter with ``data_`` prefix. Used verbatim, so
161
+ it must be usable as a GLE data filename: whitespace, control
162
+ characters and any of ``! " + / \\`` raise ``ValueError``.
163
+ height_ratios : sequence of float, optional
164
+ Relative height of each subplot ROW for the grid built with
165
+ subsequent :meth:`Figure.add_subplot` calls, matplotlib-``gridspec``
166
+ style. ``None`` (default) keeps every row the same height. See
167
+ :class:`gleplot.figure.Figure` for full semantics (validated against
168
+ the actual row count at GLE-generation time, once every
169
+ ``add_subplot`` has been made).
170
+ width_ratios : sequence of float, optional
171
+ Relative width of each subplot COLUMN. Same semantics as
172
+ ``height_ratios``, for columns.
173
+ **kwargs
174
+ Any other matplotlib keyword (``num``, ``facecolor``, ...) warns and
175
+ is ignored.
176
+
177
+ Returns
178
+ -------
179
+ Figure
180
+ New figure object
181
+
182
+ Examples
183
+ --------
184
+ Create a figure with default settings:
185
+
186
+ >>> fig = glp.figure()
187
+
188
+ Create a figure with custom style:
189
+
190
+ >>> style = glp.GLEStyleConfig(font='texcmss', fontsize=12)
191
+ >>> fig = glp.figure(style=style)
192
+
193
+ Or modify global defaults:
194
+
195
+ >>> glp.GlobalConfig.style.font = 'texcmss'
196
+ >>> fig = glp.figure() # Will use Computer Modern Sans Serif
197
+
198
+ A 5-row grid built with add_subplot, with a short 4th "separator" row:
199
+
200
+ >>> fig = glp.figure(figsize=(3.4, 5.2), height_ratios=[3, 3, 3, 1, 4])
201
+ >>> axes = [fig.add_subplot(5, 1, i) for i in range(1, 6)]
202
+ """
203
+ _warn.warn_unsupported_keywords("figure", kwargs)
204
+ global _current_figure
205
+ _current_figure = Figure(
206
+ figsize=figsize,
207
+ dpi=dpi,
208
+ style=style,
209
+ graph=graph,
210
+ marker=marker,
211
+ data_prefix=data_prefix,
212
+ height_ratios=height_ratios,
213
+ width_ratios=width_ratios,
214
+ )
215
+ return _current_figure
216
+
217
+
218
+ def gca():
219
+ """Get current axes."""
220
+ if _current_figure is None:
221
+ figure()
222
+ return _current_figure.gca()
223
+
224
+
225
+ def gcf():
226
+ """Get current figure."""
227
+ if _current_figure is None:
228
+ figure()
229
+ return _current_figure
230
+
231
+
232
+ def plot(*args, **kwargs):
233
+ """Plot on current axes."""
234
+ return gca().plot(*args, **kwargs)
235
+
236
+
237
+ def semilogx(*args, **kwargs):
238
+ """Plot with a log x axis on current axes."""
239
+ return gca().semilogx(*args, **kwargs)
240
+
241
+
242
+ def semilogy(*args, **kwargs):
243
+ """Plot with a log y axis on current axes."""
244
+ return gca().semilogy(*args, **kwargs)
245
+
246
+
247
+ def loglog(*args, **kwargs):
248
+ """Plot with log x and y axes on current axes."""
249
+ return gca().loglog(*args, **kwargs)
250
+
251
+
252
+ def twinx(ax=None):
253
+ """The right-hand y scale of ``ax`` (default: current axes)."""
254
+ return (gca() if ax is None else ax).twinx()
255
+
256
+
257
+ def twiny(ax=None):
258
+ """The top x scale of ``ax`` (default: current axes)."""
259
+ return (gca() if ax is None else ax).twiny()
260
+
261
+
262
+ def axis(arg=None, /, *, emit=True, **kwargs):
263
+ """Get or set the limits of, or hide, the current axes. See
264
+ :meth:`Axes.axis`."""
265
+ return gca().axis(arg, emit=emit, **kwargs)
266
+
267
+
268
+ def step(*args, **kwargs):
269
+ """Step plot on current axes. See :meth:`gleplot.Axes.step`."""
270
+ return gca().step(*args, **kwargs)
271
+
272
+
273
+ def stem(*args, **kwargs):
274
+ """Stem plot on current axes. See :meth:`gleplot.Axes.stem`."""
275
+ return gca().stem(*args, **kwargs)
276
+
277
+
278
+ def hist(*args, **kwargs):
279
+ """Histogram on the current axes. See :meth:`gleplot.Axes.hist`."""
280
+ return gca().hist(*args, **kwargs)
281
+
282
+
283
+ def scatter(*args, **kwargs):
284
+ """Scatter on current axes."""
285
+ return gca().scatter(*args, **kwargs)
286
+
287
+
288
+ def bar(*args, **kwargs):
289
+ """Bar chart on the current axes. See :meth:`gleplot.Axes.bar`."""
290
+ return gca().bar(*args, **kwargs)
291
+
292
+
293
+ def barh(*args, **kwargs):
294
+ """Horizontal bars on the current axes. See :meth:`gleplot.Axes.barh`."""
295
+ return gca().barh(*args, **kwargs)
296
+
297
+
298
+ def fill_between(*args, **kwargs):
299
+ """Fill between on current axes. See :meth:`gleplot.Axes.fill_between`."""
300
+ return gca().fill_between(*args, **kwargs)
301
+
302
+
303
+ def fill_betweenx(*args, **kwargs):
304
+ """Fill between two x curves on the current axes.
305
+
306
+ See :meth:`gleplot.Axes.fill_betweenx`.
307
+ """
308
+ return gca().fill_betweenx(*args, **kwargs)
309
+
310
+
311
+ def stackplot(*args, **kwargs):
312
+ """Stacked bands on the current axes. See :meth:`gleplot.Axes.stackplot`."""
313
+ return gca().stackplot(*args, **kwargs)
314
+
315
+
316
+ def fill(*args, **kwargs):
317
+ """Fill a polygon on the current axes. See :meth:`gleplot.Axes.fill`."""
318
+ return gca().fill(*args, **kwargs)
319
+
320
+
321
+ def errorbar(*args, **kwargs):
322
+ """Error bar plot on current axes."""
323
+ return gca().errorbar(*args, **kwargs)
324
+
325
+
326
+ def text(*args, **kwargs):
327
+ """Add text annotation on current axes."""
328
+ return gca().text(*args, **kwargs)
329
+
330
+
331
+ def annotate(*args, **kwargs):
332
+ """Annotate a point on current axes, optionally with an arrow."""
333
+ return gca().annotate(*args, **kwargs)
334
+
335
+
336
+ def axvline(*args, **kwargs):
337
+ """Vertical reference line on current axes."""
338
+ return gca().axvline(*args, **kwargs)
339
+
340
+
341
+ def axhline(*args, **kwargs):
342
+ """Horizontal reference line on current axes."""
343
+ return gca().axhline(*args, **kwargs)
344
+
345
+
346
+ def hlines(*args, **kwargs):
347
+ """Horizontal segments on the current axes. See :meth:`gleplot.Axes.hlines`."""
348
+ return gca().hlines(*args, **kwargs)
349
+
350
+
351
+ def vlines(*args, **kwargs):
352
+ """Vertical segments on the current axes. See :meth:`gleplot.Axes.vlines`."""
353
+ return gca().vlines(*args, **kwargs)
354
+
355
+
356
+ def axvspan(*args, **kwargs):
357
+ """Shaded vertical band on current axes."""
358
+ return gca().axvspan(*args, **kwargs)
359
+
360
+
361
+ def axhspan(*args, **kwargs):
362
+ """Shaded horizontal band on current axes."""
363
+ return gca().axhspan(*args, **kwargs)
364
+
365
+
366
+ def imshow(*args, **kwargs):
367
+ """Display gridded data as a heatmap on current axes."""
368
+ return gca().imshow(*args, **kwargs)
369
+
370
+
371
+ def pcolormesh(*args, **kwargs):
372
+ """Colour the cells of a rectangular grid on current axes."""
373
+ return gca().pcolormesh(*args, **kwargs)
374
+
375
+
376
+ def contour(*args, **kwargs):
377
+ """Draw contour lines on current axes."""
378
+ return gca().contour(*args, **kwargs)
379
+
380
+
381
+ def contourf(*args, **kwargs):
382
+ """Fill the bands between contour levels on current axes."""
383
+ return gca().contourf(*args, **kwargs)
384
+
385
+
386
+ def tripcolor(*args, **kwargs):
387
+ """Scattered-data heatmap on current axes."""
388
+ return gca().tripcolor(*args, **kwargs)
389
+
390
+
391
+ def tricontour(*args, **kwargs):
392
+ """Scattered-data contour lines on current axes."""
393
+ return gca().tricontour(*args, **kwargs)
394
+
395
+
396
+ def colorbar(mappable=None, cax=None, ax=None, **kwargs):
397
+ """Attach a colorbar to a heatmap or colour-mapped scatter on the current figure.
398
+
399
+ See :meth:`Figure.colorbar`.
400
+ """
401
+ return gcf().colorbar(mappable, cax, ax, **kwargs)
402
+
403
+
404
+ def subplots(
405
+ nrows: int = 1,
406
+ ncols: int = 1,
407
+ *,
408
+ sharex: Union[bool, str] = False,
409
+ sharey: Union[bool, str] = False,
410
+ squeeze: bool = True,
411
+ width_ratios=None,
412
+ height_ratios=None,
413
+ subplot_kw=None,
414
+ gridspec_kw=None,
415
+ figsize=None,
416
+ dpi=100,
417
+ style=None,
418
+ graph=None,
419
+ marker=None,
420
+ data_prefix=None,
421
+ **fig_kw,
422
+ ):
423
+ """
424
+ Create a figure and a set of subplots.
425
+
426
+ Convenience function matching ``matplotlib.pyplot.subplots()``.
427
+
428
+ Parameters
429
+ ----------
430
+ nrows : int, optional
431
+ Number of rows of subplots. Default: 1
432
+ ncols : int, optional
433
+ Number of columns of subplots. Default: 1
434
+ sharex : bool or {'all', 'none', 'row', 'col'}, default: False
435
+ As in matplotlib: ``True`` or ``'all'`` gives every subplot one x
436
+ range, ``'col'`` one per column and ``'row'`` one per row. With
437
+ ``True`` and ``'col'`` only the bottom row shows x tick labels and
438
+ the x-axis label. ``False`` or ``'none'`` shares nothing; another
439
+ value raises ``ValueError``.
440
+ sharey : bool or {'all', 'none', 'row', 'col'}, default: False
441
+ The same for the y axis: ``'row'`` gives one y range per row and,
442
+ like ``True``, shows y tick labels only in the leftmost column;
443
+ ``'col'`` gives one per column.
444
+ squeeze : bool, default: True
445
+ As in matplotlib: if True, drop the extra dimensions of the returned
446
+ array, so a single subplot comes back as an :class:`Axes` and a
447
+ single row or column as a 1-D array. If False, always return a 2-D
448
+ array, even for a 1x1 grid.
449
+ width_ratios : sequence of float, optional
450
+ Relative width of each of the ``ncols`` subplot columns, matplotlib-
451
+ ``gridspec`` style (e.g. ``[1, 3]`` makes the second of two columns
452
+ three times as wide). Must have length ``ncols`` if given. ``None``
453
+ (default) keeps every column the same width. See
454
+ :class:`gleplot.figure.Figure` for full semantics (validated against
455
+ the actual column count at GLE-generation time).
456
+ height_ratios : sequence of float, optional
457
+ Relative height of each of the ``nrows`` subplot rows (e.g.
458
+ ``[3, 3, 3, 1, 4]`` for 5 rows whose 4th is thin). Same semantics as
459
+ ``width_ratios``, for rows; must have length ``nrows`` if given.
460
+ subplot_kw : dict, optional
461
+ As in matplotlib, keywords for each :meth:`Figure.add_subplot` call,
462
+ such as ``projection='polar'``.
463
+ gridspec_kw : dict, optional
464
+ As in matplotlib, the grid's layout. ``width_ratios`` and
465
+ ``height_ratios`` are as the parameters (giving one both ways raises
466
+ ``ValueError``); ``left``, ``right``, ``bottom``, ``top``, ``wspace``
467
+ and ``hspace`` are passed to :meth:`Figure.subplots_adjust`; other
468
+ keys warn and are ignored.
469
+ figsize : tuple, optional
470
+ Figure size (width, height) in inches. If None, auto-scales
471
+ based on grid size (6 inches per column, 4 inches per row).
472
+ dpi : int, optional
473
+ Dots per inch. Default: 100
474
+ style : GLEStyleConfig, optional
475
+ Style configuration.
476
+ graph : GLEGraphConfig, optional
477
+ Graph configuration.
478
+ marker : GLEMarkerConfig, optional
479
+ Marker configuration.
480
+ data_prefix : str, optional
481
+ Custom prefix for data file names (e.g., 'test9' creates 'test9_0.dat', 'test9_1.dat').
482
+ If None, uses global counter with ``data_`` prefix. Used verbatim, so
483
+ it must be usable as a GLE data filename: whitespace, control
484
+ characters and any of ``! " + / \\`` raise ``ValueError``.
485
+ **fig_kw
486
+ matplotlib's other :func:`matplotlib.pyplot.figure` keywords, such
487
+ as ``num`` or ``layout``. gleplot has none of them: they warn and
488
+ are ignored.
489
+
490
+ Returns
491
+ -------
492
+ fig : Figure
493
+ The figure object.
494
+ axes : Axes or numpy.ndarray of Axes
495
+ The subplots in a ``(nrows, ncols)`` object array, indexed
496
+ ``axes[row, col]``, squeezed as described for ``squeeze``.
497
+
498
+ Notes
499
+ -----
500
+ As in matplotlib, every parameter after ``ncols`` is keyword-only.
501
+ ``figsize`` and the other figure settings are the keywords
502
+ :func:`figure` takes; ``figsize`` is in inches.
503
+
504
+ Examples
505
+ --------
506
+ Single plot:
507
+
508
+ >>> fig, ax = glp.subplots()
509
+ >>> ax.plot(x, y)
510
+
511
+ 2x2 grid:
512
+
513
+ >>> fig, axes = glp.subplots(2, 2, figsize=(12, 10))
514
+ >>> axes[0, 0].plot(x, y1) # top-left
515
+ >>> axes[0, 1].scatter(x, y2) # top-right
516
+ >>> axes[1, 0].bar(x, y3) # bottom-left
517
+ >>> axes[1, 1].plot(x, y4) # bottom-right
518
+
519
+ Shared x-axis (stacked plots):
520
+
521
+ >>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(8, 12))
522
+ >>> # Only bottom subplot shows x-axis label and ticks
523
+
524
+ Stacked panels with a short separator row (unequal row heights):
525
+
526
+ >>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(3.4, 4),
527
+ ... height_ratios=[3, 3, 1])
528
+ >>> # axes[2] gets 1/7 of the plotting height, axes[0]/axes[1] get 3/7 each
529
+ """
530
+ global _current_figure
531
+
532
+ for name, value in (("nrows", nrows), ("ncols", ncols)):
533
+ if not isinstance(value, (int, np.integer)):
534
+ raise TypeError(f"subplots({name}={value!r}): expected a positive int")
535
+ if value < 1:
536
+ raise ValueError(f"subplots({name}={value!r}): expected a positive int")
537
+
538
+ grid = dict(gridspec_kw or {})
539
+ for name, value in (
540
+ ("width_ratios", width_ratios),
541
+ ("height_ratios", height_ratios),
542
+ ):
543
+ if name in grid and value is not None:
544
+ raise ValueError(
545
+ f"subplots(): {name!r} was given both as a parameter and as a "
546
+ "key of gridspec_kw; give it once."
547
+ )
548
+ width_ratios = grid.pop("width_ratios", width_ratios)
549
+ height_ratios = grid.pop("height_ratios", height_ratios)
550
+ adjust = {
551
+ key: grid.pop(key)
552
+ for key in ("left", "right", "bottom", "top", "wspace", "hspace")
553
+ if key in grid
554
+ }
555
+ _warn.warn_unsupported_keywords(
556
+ "subplots", list(fig_kw) + [f"gridspec_kw[{key!r}]" for key in grid]
557
+ )
558
+
559
+ if figsize is None:
560
+ figsize = (max(6, 6 * ncols), max(4, 4 * nrows))
561
+
562
+ fig = Figure(
563
+ figsize=figsize,
564
+ dpi=dpi,
565
+ style=style,
566
+ graph=graph,
567
+ marker=marker,
568
+ sharex=sharex,
569
+ sharey=sharey,
570
+ data_prefix=data_prefix,
571
+ height_ratios=height_ratios,
572
+ width_ratios=width_ratios,
573
+ )
574
+ try:
575
+ fig.subplots_adjust(**adjust)
576
+ except ValueError as err:
577
+ raise ValueError(f"subplots(gridspec_kw={gridspec_kw!r}): {err}") from None
578
+
579
+ axes = np.empty((nrows, ncols), dtype=object)
580
+ for idx in range(nrows * ncols):
581
+ axes.flat[idx] = fig.add_subplot(nrows, ncols, idx + 1, **(subplot_kw or {}))
582
+ _current_figure = fig
583
+
584
+ if squeeze:
585
+ return fig, axes.item() if axes.size == 1 else axes.squeeze()
586
+ return fig, axes
587
+
588
+
589
+ def xlabel(label: str, fontdict=None, labelpad=None, *, loc=None, **kwargs):
590
+ """Set x label on current axes: :meth:`Axes.set_xlabel` on :func:`gca`."""
591
+ return gca().set_xlabel(
592
+ label, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
593
+ )
594
+
595
+
596
+ def ylabel(label: str, fontdict=None, labelpad=None, *, loc=None, **kwargs):
597
+ """Set y label on current axes: :meth:`Axes.set_ylabel` on :func:`gca`."""
598
+ return gca().set_ylabel(
599
+ label, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
600
+ )
601
+
602
+
603
+ def title(label: str, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
604
+ """Set title on current axes: :meth:`Axes.set_title` on :func:`gca`.
605
+
606
+ ``y`` warns and is ignored, as on :meth:`Axes.set_title`.
607
+ """
608
+ if y is not None:
609
+ kwargs["y"] = y
610
+ return gca().set_title(label, fontdict, loc, pad, **kwargs)
611
+
612
+
613
+ def legend(**kwargs):
614
+ """Add legend to current axes."""
615
+ return gca().legend(**kwargs)
616
+
617
+
618
+ def savefig(filepath: str, **kwargs):
619
+ """Save current figure: :meth:`Figure.savefig` on :func:`gcf`.
620
+
621
+ A keyword ``Figure.savefig`` does not take warns and is ignored.
622
+ """
623
+ return gcf().savefig(filepath, **kwargs)
624
+
625
+
626
+ def show():
627
+ """Show the current figure, as :func:`view` does with its defaults.
628
+
629
+ In a Jupyter notebook the figure is displayed inline. Elsewhere it is
630
+ rendered to a temporary PNG and nothing is printed: open the returned path.
631
+
632
+ Returns
633
+ -------
634
+ Path or None
635
+ Path to the temporary file, or None when displayed inline in Jupyter.
636
+
637
+ Raises
638
+ ------
639
+ RuntimeError
640
+ If GLE is not installed.
641
+ """
642
+ return gcf().view()
643
+
644
+
645
+ def view(dpi=None, format="png"):
646
+ """Display current figure inline (in Jupyter notebooks).
647
+
648
+ Parameters
649
+ ----------
650
+ dpi : int, optional
651
+ Resolution in dots per inch. If None, uses figure's dpi setting.
652
+ format : {'png', 'pdf'}, optional
653
+ Output format. Default is 'png' for inline display.
654
+
655
+ Returns
656
+ -------
657
+ Path or None
658
+ Path to the generated file, or None when displayed inline in Jupyter.
659
+
660
+ Examples
661
+ --------
662
+ >>> import gleplot as glp
663
+ >>> fig = glp.figure()
664
+ >>> ax = fig.add_subplot(111)
665
+ >>> ax.plot([1, 2, 3], [1, 4, 9])
666
+ >>> glp.view() # Display in notebook
667
+ """
668
+ return gcf().view(dpi=dpi, format=format)
669
+
670
+
671
+ def close(fig=None):
672
+ """Close a figure, as ``matplotlib.pyplot.close``.
673
+
674
+ Parameters
675
+ ----------
676
+ fig : None, Figure or 'all', optional
677
+ ``None`` (default) or ``'all'`` closes the current figure, the one
678
+ figure gleplot keeps track of; a :class:`Figure` closes that figure.
679
+ gleplot does not number or name its figures, so an int or another
680
+ string matches no figure: it warns and closes nothing.
681
+ """
682
+ global _current_figure
683
+ if fig is None or (isinstance(fig, str) and fig == "all"):
684
+ fig = _current_figure
685
+ elif isinstance(fig, (int, str)) and not isinstance(fig, bool):
686
+ _warn.warn_external(
687
+ f"close({fig!r}) closes nothing: gleplot does not number or name "
688
+ "its figures. Pass the Figure, 'all' or None."
689
+ )
690
+ return
691
+ elif not isinstance(fig, Figure):
692
+ raise TypeError(
693
+ f"close({fig!r}): expected a Figure, 'all' or None, "
694
+ f"not {type(fig).__name__}."
695
+ )
696
+ if fig is not None:
697
+ fig.close()
698
+ if fig is _current_figure:
699
+ _current_figure = None
700
+
701
+
702
+ __all__ = [
703
+ "Figure",
704
+ "Axes",
705
+ # Light validation of a GLE tick-label number format string ("fix 1",
706
+ # "sci 2 10", ...), for callers building one interactively.
707
+ "validate_tick_format",
708
+ "figure",
709
+ "gca",
710
+ "gcf",
711
+ "plot",
712
+ "semilogx",
713
+ "semilogy",
714
+ "loglog",
715
+ "twinx",
716
+ "twiny",
717
+ "axis",
718
+ "step",
719
+ "stem",
720
+ "hist",
721
+ "scatter",
722
+ "bar",
723
+ "barh",
724
+ "fill_between",
725
+ "fill_betweenx",
726
+ "stackplot",
727
+ "fill",
728
+ "errorbar",
729
+ "text",
730
+ "annotate",
731
+ "axvline",
732
+ "axhline",
733
+ "hlines",
734
+ "vlines",
735
+ "axvspan",
736
+ "axhspan",
737
+ "imshow",
738
+ "pcolormesh",
739
+ "contour",
740
+ "contourf",
741
+ "tripcolor",
742
+ "tricontour",
743
+ "colorbar",
744
+ "subplots",
745
+ "xlabel",
746
+ "ylabel",
747
+ "title",
748
+ "legend",
749
+ "savefig",
750
+ "view",
751
+ "show",
752
+ "close",
753
+ "rgb_to_gle",
754
+ "get_color_palette",
755
+ "get_gle_marker",
756
+ "mathtext_to_gle",
757
+ "GLECompiler",
758
+ "GLEStyleConfig",
759
+ "GLEGraphConfig",
760
+ "GLEMarkerConfig",
761
+ "GlobalConfig",
762
+ "open_gle",
763
+ "DataSource",
764
+ "InlineData",
765
+ "ColumnRef",
766
+ "GridRef",
767
+ "DataProvider",
768
+ "TableData",
769
+ "DictDataProvider",
770
+ "DanglingSourceRef",
771
+ "DanglingSourceWarning",
772
+ ]