Source code for gleplot

"""
gleplot - write standard GLE from Python, with matplotlib-shaped names

A Python library that writes GLE (Graphics Layout Engine) scripts for
publication-quality vector graphics, through matplotlib-shaped calls.

Features
--------
- Matplotlib-compatible API (plot, scatter, bar, fill_between, errorbar)
- Text annotations and arrows in data coordinates or axes fractions (text,
  annotate)
- Subplots with flexible grid layouts (subplots, add_subplot)
- Native vector graphics output (PDF, PNG, EPS)
- Inline display in Jupyter notebooks (view)
- Support for line styles, markers, and colors
- Error bars (symmetric, asymmetric, horizontal)
- Logarithmic scales
- Legend and axis labels
- Semantic per-series data file naming (data_name) and figure-level prefixes (data_prefix)
- Direct GLE script generation

Usage
-----
    import gleplot as glp

    fig = glp.figure(figsize=(8, 6))
    ax = fig.add_subplot(111)

    ax.plot([1, 2, 3], [1, 4, 9], 'b-', label='quadratic')
    ax.scatter([1, 2, 3], [1, 2, 3], color='red', label='points')

    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_title('Example Plot')
    ax.legend()

    fig.savefig('output.pdf')  # Saves as PDF
    fig.savefig('output.gle')  # Saves as GLE script only
    fig.view()  # Display inline in Jupyter notebook

Classes
-------
Figure
    Matplotlib-like figure container
Axes
    Matplotlib-like axes for plotting

Functions
---------
figure(figsize=(8, 6), dpi=100)
    Create a new figure
"""

__version__ = "5.6.3"
__author__ = "gleplot contributors"

from typing import Union

import numpy as np

from . import _warn
from .axes import Axes, validate_tick_format
from .colors import get_color_palette, rgb_to_gle
from .compiler import GLECompiler
from .config import (
    GLEGraphConfig,
    GLEMarkerConfig,
    GLEStyleConfig,
    GlobalConfig,
)
from .figure import Figure
from .markers import get_gle_marker
from .mathtext import mathtext_to_gle

# Series data sources: where a series' numbers come from. The scripting API
# always produces InlineData (baked arrays) and never needs these; they are
# the API an embedding application uses to point series at its own tables.
from .sources import (
    ColumnRef,
    DanglingSourceRef,
    DanglingSourceWarning,
    DataProvider,
    DataSource,
    DictDataProvider,
    GridRef,
    InlineData,
    TableData,
)

# Module-level convenience functions (for matplotlib compatibility)

_current_figure = None


[docs] def open_gle(path, *, base_dir=None) -> Figure: """Open a ``.gle`` file (or GLE source text) as a gleplot :class:`Figure`. Convenience wrapper around :func:`gleplot.parser.recognizer.parse_gle_figure` that returns just the reconstructed figure. Each recovery note (something kept as raw GLE, guessed, or converted) is raised as a ``UserWarning`` whose text is ``"category: message"``. Use ``parse_gle_figure`` directly to get the notes as data instead. Parameters ---------- path : str or pathlib.Path Path to a ``.gle`` file, or raw GLE source text. base_dir : str or pathlib.Path, optional Directory for resolving relative ``data`` references when ``path`` is raw source text. Returns ------- Figure Warns ----- UserWarning One per recovery note. Python's default warning filter shows a message it has already shown from the same line only once; use ``parse_gle_figure`` for the full list and each note's line span. """ from .parser.recognizer import parse_gle_figure result = parse_gle_figure(path, base_dir=base_dir) for warning in result.warnings: _warn.warn_external(warning) return result.figure
[docs] def figure( figsize=(8, 6), dpi=100, style=None, graph=None, marker=None, data_prefix=None, height_ratios=None, width_ratios=None, **kwargs, ) -> Figure: """ Create a new figure. Parameters ---------- figsize : tuple, optional Figure size (width, height) in inches. Default: (8, 6) dpi : int, optional Dots per inch. Default: 100 style : GLEStyleConfig, optional Style configuration. If None, uses global default. graph : GLEGraphConfig, optional Graph configuration. If None, uses global default. marker : GLEMarkerConfig, optional Marker configuration. If None, uses global default. data_prefix : str, optional Custom prefix for data file names (e.g., 'test9' creates 'test9_0.dat', 'test9_1.dat'). If None, uses global counter with ``data_`` prefix. Used verbatim, so it must be usable as a GLE data filename: whitespace, control characters and any of ``! " + / \\`` raise ``ValueError``. height_ratios : sequence of float, optional Relative height of each subplot ROW for the grid built with subsequent :meth:`Figure.add_subplot` calls, matplotlib-``gridspec`` style. ``None`` (default) keeps every row the same height. See :class:`gleplot.figure.Figure` for full semantics (validated against the actual row count at GLE-generation time, once every ``add_subplot`` has been made). width_ratios : sequence of float, optional Relative width of each subplot COLUMN. Same semantics as ``height_ratios``, for columns. **kwargs Any other matplotlib keyword (``num``, ``facecolor``, ...) warns and is ignored. Returns ------- Figure New figure object Examples -------- Create a figure with default settings: >>> fig = glp.figure() Create a figure with custom style: >>> style = glp.GLEStyleConfig(font='texcmss', fontsize=12) >>> fig = glp.figure(style=style) Or modify global defaults: >>> glp.GlobalConfig.style.font = 'texcmss' >>> fig = glp.figure() # Will use Computer Modern Sans Serif A 5-row grid built with add_subplot, with a short 4th "separator" row: >>> fig = glp.figure(figsize=(3.4, 5.2), height_ratios=[3, 3, 3, 1, 4]) >>> axes = [fig.add_subplot(5, 1, i) for i in range(1, 6)] """ _warn.warn_unsupported_keywords("figure", kwargs) global _current_figure _current_figure = Figure( figsize=figsize, dpi=dpi, style=style, graph=graph, marker=marker, data_prefix=data_prefix, height_ratios=height_ratios, width_ratios=width_ratios, ) return _current_figure
[docs] def gca(): """Get current axes.""" if _current_figure is None: figure() return _current_figure.gca()
[docs] def gcf(): """Get current figure.""" if _current_figure is None: figure() return _current_figure
[docs] def plot(*args, **kwargs): """Plot on current axes.""" return gca().plot(*args, **kwargs)
[docs] def semilogx(*args, **kwargs): """Plot with a log x axis on current axes.""" return gca().semilogx(*args, **kwargs)
[docs] def semilogy(*args, **kwargs): """Plot with a log y axis on current axes.""" return gca().semilogy(*args, **kwargs)
[docs] def loglog(*args, **kwargs): """Plot with log x and y axes on current axes.""" return gca().loglog(*args, **kwargs)
[docs] def twinx(ax=None): """The right-hand y scale of ``ax`` (default: current axes).""" return (gca() if ax is None else ax).twinx()
[docs] def twiny(ax=None): """The top x scale of ``ax`` (default: current axes).""" return (gca() if ax is None else ax).twiny()
[docs] def axis(arg=None, /, *, emit=True, **kwargs): """Get or set the limits of, or hide, the current axes. See :meth:`Axes.axis`.""" return gca().axis(arg, emit=emit, **kwargs)
[docs] def step(*args, **kwargs): """Step plot on current axes. See :meth:`gleplot.Axes.step`.""" return gca().step(*args, **kwargs)
[docs] def stem(*args, **kwargs): """Stem plot on current axes. See :meth:`gleplot.Axes.stem`.""" return gca().stem(*args, **kwargs)
[docs] def hist(*args, **kwargs): """Histogram on the current axes. See :meth:`gleplot.Axes.hist`.""" return gca().hist(*args, **kwargs)
[docs] def scatter(*args, **kwargs): """Scatter on current axes.""" return gca().scatter(*args, **kwargs)
[docs] def bar(*args, **kwargs): """Bar chart on current axes.""" return gca().bar(*args, **kwargs)
[docs] def barh(*args, **kwargs): """Horizontal bars on the current axes. See :meth:`gleplot.Axes.barh`.""" return gca().barh(*args, **kwargs)
[docs] def fill_between(*args, **kwargs): """Fill between on current axes. See :meth:`gleplot.Axes.fill_between`.""" return gca().fill_between(*args, **kwargs)
[docs] def fill_betweenx(*args, **kwargs): """Fill between two x curves on the current axes. See :meth:`gleplot.Axes.fill_betweenx`. """ return gca().fill_betweenx(*args, **kwargs)
[docs] def stackplot(*args, **kwargs): """Stacked bands on the current axes. See :meth:`gleplot.Axes.stackplot`.""" return gca().stackplot(*args, **kwargs)
[docs] def fill(*args, **kwargs): """Fill a polygon on the current axes. See :meth:`gleplot.Axes.fill`.""" return gca().fill(*args, **kwargs)
[docs] def errorbar(*args, **kwargs): """Error bar plot on current axes.""" return gca().errorbar(*args, **kwargs)
[docs] def text(*args, **kwargs): """Add text annotation on current axes.""" return gca().text(*args, **kwargs)
[docs] def annotate(*args, **kwargs): """Annotate a point on current axes, optionally with an arrow.""" return gca().annotate(*args, **kwargs)
[docs] def axvline(*args, **kwargs): """Vertical reference line on current axes.""" return gca().axvline(*args, **kwargs)
[docs] def axhline(*args, **kwargs): """Horizontal reference line on current axes.""" return gca().axhline(*args, **kwargs)
[docs] def hlines(*args, **kwargs): """Horizontal segments on the current axes. See :meth:`gleplot.Axes.hlines`.""" return gca().hlines(*args, **kwargs)
[docs] def vlines(*args, **kwargs): """Vertical segments on the current axes. See :meth:`gleplot.Axes.vlines`.""" return gca().vlines(*args, **kwargs)
[docs] def axvspan(*args, **kwargs): """Shaded vertical band on current axes.""" return gca().axvspan(*args, **kwargs)
[docs] def axhspan(*args, **kwargs): """Shaded horizontal band on current axes.""" return gca().axhspan(*args, **kwargs)
[docs] def imshow(*args, **kwargs): """Display gridded data as a heatmap on current axes.""" return gca().imshow(*args, **kwargs)
[docs] def pcolormesh(*args, **kwargs): """Colour the cells of a rectangular grid on current axes.""" return gca().pcolormesh(*args, **kwargs)
[docs] def contour(*args, **kwargs): """Draw contour lines on current axes.""" return gca().contour(*args, **kwargs)
[docs] def contourf(*args, **kwargs): """Fill the bands between contour levels on current axes.""" return gca().contourf(*args, **kwargs)
[docs] def tripcolor(*args, **kwargs): """Scattered-data heatmap on current axes.""" return gca().tripcolor(*args, **kwargs)
[docs] def tricontour(*args, **kwargs): """Scattered-data contour lines on current axes.""" return gca().tricontour(*args, **kwargs)
[docs] def colorbar(mappable=None, cax=None, ax=None, **kwargs): """Attach a colorbar to a heatmap or colour-mapped scatter on the current figure. See :meth:`Figure.colorbar`. """ return gcf().colorbar(mappable, cax, ax, **kwargs)
[docs] def subplots( nrows: int = 1, ncols: int = 1, *, sharex: Union[bool, str] = False, sharey: Union[bool, str] = False, squeeze: bool = True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, figsize=None, dpi=100, style=None, graph=None, marker=None, data_prefix=None, **fig_kw, ): """ Create a figure and a set of subplots. Convenience function matching ``matplotlib.pyplot.subplots()``. Parameters ---------- nrows : int, optional Number of rows of subplots. Default: 1 ncols : int, optional Number of columns of subplots. Default: 1 sharex : bool or {'all', 'none', 'row', 'col'}, default: False As in matplotlib: ``True`` or ``'all'`` gives every subplot one x range, ``'col'`` one per column and ``'row'`` one per row. With ``True`` and ``'col'`` only the bottom row shows x tick labels and the x-axis label. ``False`` or ``'none'`` shares nothing; another value raises ``ValueError``. sharey : bool or {'all', 'none', 'row', 'col'}, default: False The same for the y axis: ``'row'`` gives one y range per row and, like ``True``, shows y tick labels only in the leftmost column; ``'col'`` gives one per column. squeeze : bool, default: True As in matplotlib: if True, drop the extra dimensions of the returned array, so a single subplot comes back as an :class:`Axes` and a single row or column as a 1-D array. If False, always return a 2-D array, even for a 1x1 grid. width_ratios : sequence of float, optional Relative width of each of the ``ncols`` subplot columns, matplotlib- ``gridspec`` style (e.g. ``[1, 3]`` makes the second of two columns three times as wide). Must have length ``ncols`` if given. ``None`` (default) keeps every column the same width. See :class:`gleplot.figure.Figure` for full semantics (validated against the actual column count at GLE-generation time). height_ratios : sequence of float, optional Relative height of each of the ``nrows`` subplot rows (e.g. ``[3, 3, 3, 1, 4]`` for 5 rows whose 4th is thin). Same semantics as ``width_ratios``, for rows; must have length ``nrows`` if given. subplot_kw : dict, optional As in matplotlib, keywords for each :meth:`Figure.add_subplot` call, such as ``projection='polar'``. gridspec_kw : dict, optional As in matplotlib, the grid's layout. ``width_ratios`` and ``height_ratios`` are as the parameters (giving one both ways raises ``ValueError``); ``left``, ``right``, ``bottom``, ``top``, ``wspace`` and ``hspace`` are passed to :meth:`Figure.subplots_adjust`; other keys warn and are ignored. figsize : tuple, optional Figure size (width, height) in inches. If None, auto-scales based on grid size (6 inches per column, 4 inches per row). dpi : int, optional Dots per inch. Default: 100 style : GLEStyleConfig, optional Style configuration. graph : GLEGraphConfig, optional Graph configuration. marker : GLEMarkerConfig, optional Marker configuration. data_prefix : str, optional Custom prefix for data file names (e.g., 'test9' creates 'test9_0.dat', 'test9_1.dat'). If None, uses global counter with ``data_`` prefix. Used verbatim, so it must be usable as a GLE data filename: whitespace, control characters and any of ``! " + / \\`` raise ``ValueError``. **fig_kw matplotlib's other :func:`matplotlib.pyplot.figure` keywords, such as ``num`` or ``layout``. gleplot has none of them: they warn and are ignored. Returns ------- fig : Figure The figure object. axes : Axes or numpy.ndarray of Axes The subplots in a ``(nrows, ncols)`` object array, indexed ``axes[row, col]``, squeezed as described for ``squeeze``. Notes ----- As in matplotlib, every parameter after ``ncols`` is keyword-only. ``figsize`` and the other figure settings are the keywords :func:`figure` takes; ``figsize`` is in inches. Examples -------- Single plot: >>> fig, ax = glp.subplots() >>> ax.plot(x, y) 2x2 grid: >>> fig, axes = glp.subplots(2, 2, figsize=(12, 10)) >>> axes[0, 0].plot(x, y1) # top-left >>> axes[0, 1].scatter(x, y2) # top-right >>> axes[1, 0].bar(x, y3) # bottom-left >>> axes[1, 1].plot(x, y4) # bottom-right Shared x-axis (stacked plots): >>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(8, 12)) >>> # Only bottom subplot shows x-axis label and ticks Stacked panels with a short separator row (unequal row heights): >>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(3.4, 4), ... height_ratios=[3, 3, 1]) >>> # axes[2] gets 1/7 of the plotting height, axes[0]/axes[1] get 3/7 each """ global _current_figure for name, value in (("nrows", nrows), ("ncols", ncols)): if not isinstance(value, (int, np.integer)): raise TypeError(f"subplots({name}={value!r}): expected a positive int") if value < 1: raise ValueError(f"subplots({name}={value!r}): expected a positive int") grid = dict(gridspec_kw or {}) for name, value in ( ("width_ratios", width_ratios), ("height_ratios", height_ratios), ): if name in grid and value is not None: raise ValueError( f"subplots(): {name!r} was given both as a parameter and as a " "key of gridspec_kw; give it once." ) width_ratios = grid.pop("width_ratios", width_ratios) height_ratios = grid.pop("height_ratios", height_ratios) adjust = { key: grid.pop(key) for key in ("left", "right", "bottom", "top", "wspace", "hspace") if key in grid } _warn.warn_unsupported_keywords( "subplots", list(fig_kw) + [f"gridspec_kw[{key!r}]" for key in grid] ) if figsize is None: figsize = (max(6, 6 * ncols), max(4, 4 * nrows)) fig = Figure( figsize=figsize, dpi=dpi, style=style, graph=graph, marker=marker, sharex=sharex, sharey=sharey, data_prefix=data_prefix, height_ratios=height_ratios, width_ratios=width_ratios, ) try: fig.subplots_adjust(**adjust) except ValueError as err: raise ValueError(f"subplots(gridspec_kw={gridspec_kw!r}): {err}") from None axes = np.empty((nrows, ncols), dtype=object) for idx in range(nrows * ncols): axes.flat[idx] = fig.add_subplot(nrows, ncols, idx + 1, **(subplot_kw or {})) _current_figure = fig if squeeze: return fig, axes.item() if axes.size == 1 else axes.squeeze() return fig, axes
[docs] def xlabel(label: str, fontdict=None, labelpad=None, *, loc=None, **kwargs): """Set x label on current axes: :meth:`Axes.set_xlabel` on :func:`gca`.""" return gca().set_xlabel( label, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs )
[docs] def ylabel(label: str, fontdict=None, labelpad=None, *, loc=None, **kwargs): """Set y label on current axes: :meth:`Axes.set_ylabel` on :func:`gca`.""" return gca().set_ylabel( label, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs )
[docs] def title(label: str, fontdict=None, loc=None, pad=None, *, y=None, **kwargs): """Set title on current axes: :meth:`Axes.set_title` on :func:`gca`. ``y`` warns and is ignored, as on :meth:`Axes.set_title`. """ if y is not None: kwargs["y"] = y return gca().set_title(label, fontdict, loc, pad, **kwargs)
[docs] def legend(**kwargs): """Add legend to current axes.""" return gca().legend(**kwargs)
[docs] def savefig(filepath: str, **kwargs): """Save current figure: :meth:`Figure.savefig` on :func:`gcf`. A keyword ``Figure.savefig`` does not take warns and is ignored. """ return gcf().savefig(filepath, **kwargs)
[docs] def show(): """Show the current figure, as :func:`view` does with its defaults. In a Jupyter notebook the figure is displayed inline. Elsewhere it is rendered to a temporary PNG and nothing is printed: open the returned path. Returns ------- Path or None Path to the temporary file, or None when displayed inline in Jupyter. Raises ------ RuntimeError If GLE is not installed. """ return gcf().view()
[docs] def view(dpi=None, format="png"): """Display current figure inline (in Jupyter notebooks). Parameters ---------- dpi : int, optional Resolution in dots per inch. If None, uses figure's dpi setting. format : {'png', 'pdf'}, optional Output format. Default is 'png' for inline display. Returns ------- Path or None Path to the generated file, or None when displayed inline in Jupyter. Examples -------- >>> import gleplot as glp >>> fig = glp.figure() >>> ax = fig.add_subplot(111) >>> ax.plot([1, 2, 3], [1, 4, 9]) >>> glp.view() # Display in notebook """ return gcf().view(dpi=dpi, format=format)
[docs] def close(fig=None): """Close a figure, as ``matplotlib.pyplot.close``. Parameters ---------- fig : None, Figure or 'all', optional ``None`` (default) or ``'all'`` closes the current figure, the one figure gleplot keeps track of; a :class:`Figure` closes that figure. gleplot does not number or name its figures, so an int or another string matches no figure: it warns and closes nothing. """ global _current_figure if fig is None or (isinstance(fig, str) and fig == "all"): fig = _current_figure elif isinstance(fig, (int, str)) and not isinstance(fig, bool): _warn.warn_external( f"close({fig!r}) closes nothing: gleplot does not number or name " "its figures. Pass the Figure, 'all' or None." ) return elif not isinstance(fig, Figure): raise TypeError( f"close({fig!r}): expected a Figure, 'all' or None, " f"not {type(fig).__name__}." ) if fig is not None: fig.close() if fig is _current_figure: _current_figure = None
__all__ = [ "Figure", "Axes", # Light validation of a GLE tick-label number format string ("fix 1", # "sci 2 10", ...), for callers building one interactively. "validate_tick_format", "figure", "gca", "gcf", "plot", "semilogx", "semilogy", "loglog", "twinx", "twiny", "axis", "step", "stem", "hist", "scatter", "bar", "barh", "fill_between", "fill_betweenx", "stackplot", "fill", "errorbar", "text", "annotate", "axvline", "axhline", "hlines", "vlines", "axvspan", "axhspan", "imshow", "pcolormesh", "contour", "contourf", "tripcolor", "tricontour", "colorbar", "subplots", "xlabel", "ylabel", "title", "legend", "savefig", "view", "show", "close", "rgb_to_gle", "get_color_palette", "get_gle_marker", "mathtext_to_gle", "GLECompiler", "GLEStyleConfig", "GLEGraphConfig", "GLEMarkerConfig", "GlobalConfig", "open_gle", "DataSource", "InlineData", "ColumnRef", "GridRef", "DataProvider", "TableData", "DictDataProvider", "DanglingSourceRef", "DanglingSourceWarning", ]