Module functions

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

Plotting helpers

gleplot.figure(figsize=(8, 6), dpi=100, style=None, graph=None, marker=None, data_prefix=None, height_ratios=None, width_ratios=None, **kwargs)[source]

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 Figure.add_subplot() calls, matplotlib-gridspec style. None (default) keeps every row the same height. See 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:

New figure object

Return type:

Figure

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)]
gleplot.gca()[source]

Get current axes.

gleplot.gcf()[source]

Get current figure.

gleplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=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)[source]

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 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 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 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 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 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 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
gleplot.plot(*args, **kwargs)[source]

Plot on current axes.

gleplot.semilogx(*args, **kwargs)[source]

Plot with a log x axis on current axes.

gleplot.semilogy(*args, **kwargs)[source]

Plot with a log y axis on current axes.

gleplot.loglog(*args, **kwargs)[source]

Plot with log x and y axes on current axes.

gleplot.step(*args, **kwargs)[source]

Step plot on current axes. See gleplot.Axes.step().

gleplot.stem(*args, **kwargs)[source]

Stem plot on current axes. See gleplot.Axes.stem().

gleplot.hist(*args, **kwargs)[source]

Histogram on the current axes. See gleplot.Axes.hist().

gleplot.scatter(*args, **kwargs)[source]

Scatter on current axes.

gleplot.bar(*args, **kwargs)[source]

Bar chart on current axes.

gleplot.barh(*args, **kwargs)[source]

Horizontal bars on the current axes. See gleplot.Axes.barh().

gleplot.fill_between(*args, **kwargs)[source]

Fill between on current axes. See gleplot.Axes.fill_between().

gleplot.fill_betweenx(*args, **kwargs)[source]

Fill between two x curves on the current axes.

See gleplot.Axes.fill_betweenx().

gleplot.stackplot(*args, **kwargs)[source]

Stacked bands on the current axes. See gleplot.Axes.stackplot().

gleplot.fill(*args, **kwargs)[source]

Fill a polygon on the current axes. See gleplot.Axes.fill().

gleplot.errorbar(*args, **kwargs)[source]

Error bar plot on current axes.

gleplot.imshow(*args, **kwargs)[source]

Display gridded data as a heatmap on current axes.

gleplot.pcolormesh(*args, **kwargs)[source]

Colour the cells of a rectangular grid on current axes.

gleplot.contour(*args, **kwargs)[source]

Draw contour lines on current axes.

gleplot.contourf(*args, **kwargs)[source]

Fill the bands between contour levels on current axes.

gleplot.tripcolor(*args, **kwargs)[source]

Scattered-data heatmap on current axes.

gleplot.tricontour(*args, **kwargs)[source]

Scattered-data contour lines on current axes.

gleplot.colorbar(mappable=None, cax=None, ax=None, **kwargs)[source]

Attach a colorbar to a heatmap or colour-mapped scatter on the current figure.

See Figure.colorbar().

gleplot.text(*args, **kwargs)[source]

Add text annotation on current axes.

gleplot.annotate(*args, **kwargs)[source]

Annotate a point on current axes, optionally with an arrow.

gleplot.axvline(*args, **kwargs)[source]

Vertical reference line on current axes.

gleplot.axhline(*args, **kwargs)[source]

Horizontal reference line on current axes.

gleplot.hlines(*args, **kwargs)[source]

Horizontal segments on the current axes. See gleplot.Axes.hlines().

gleplot.vlines(*args, **kwargs)[source]

Vertical segments on the current axes. See gleplot.Axes.vlines().

gleplot.axvspan(*args, **kwargs)[source]

Shaded vertical band on current axes.

gleplot.axhspan(*args, **kwargs)[source]

Shaded horizontal band on current axes.

gleplot.twinx(ax=None)[source]

The right-hand y scale of ax (default: current axes).

gleplot.twiny(ax=None)[source]

The top x scale of ax (default: current axes).

gleplot.axis(arg=None, /, *, emit=True, **kwargs)[source]

Get or set the limits of, or hide, the current axes. See Axes.axis().

gleplot.xlabel(label, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]

Set x label on current axes: Axes.set_xlabel() on gca().

Parameters:

label (str)

gleplot.ylabel(label, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]

Set y label on current axes: Axes.set_ylabel() on gca().

Parameters:

label (str)

gleplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)[source]

Set title on current axes: Axes.set_title() on gca().

y warns and is ignored, as on Axes.set_title().

Parameters:

label (str)

gleplot.legend(**kwargs)[source]

Add legend to current axes.

gleplot.savefig(filepath, **kwargs)[source]

Save current figure: Figure.savefig() on gcf().

A keyword Figure.savefig does not take warns and is ignored.

Parameters:

filepath (str)

gleplot.view(dpi=None, format='png')[source]

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 to the generated file, or None when displayed inline in Jupyter.

Return type:

Path or None

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
gleplot.show()[source]

Show the current figure, as 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 to the temporary file, or None when displayed inline in Jupyter.

Return type:

Path or None

Raises:

RuntimeError – If GLE is not installed.

gleplot.close(fig=None)[source]

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 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.

Utilities

gleplot.rgb_to_gle(color)[source]

Convert a matplotlib color specification to a GLE color token.

A recognised GLE colour name is returned as that name (uppercased); everything else is returned as an exact rgb255(r,g,b) expression, so no requested colour is ever silently replaced by a different one.

Parameters:

color (str, tuple, list or numpy.ndarray) – Matplotlib color: a name, a single-letter code, a C0..``C9`` cycle reference, a tab: name, a #RRGGBB/#RGB hex string, a grey level as a number string in [0, 1] ('0.3'), an RGB tuple/list/1-D array with components in [0, 1], or an already-formed GLE colour expression.

Returns:

A GLE colour token: an uppercase GLE colour name, or rgb255(r,g,b).

Return type:

str

Raises:
  • ValueError – For a string that is none of the forms above, a grey level outside [0, 1], or a sequence of fewer than 3 numbers.

  • TypeError – For a value that is neither a string nor a sequence of numbers.

Examples

>>> rgb_to_gle('blue')
'BLUE'
>>> rgb_to_gle('b')
'BLUE'
>>> rgb_to_gle((0.0, 0.0, 1.0))
'rgb255(0,0,255)'
>>> rgb_to_gle('#8c8c8c')
'rgb255(140,140,140)'
>>> rgb_to_gle('rgb255(140, 140, 140)')
'rgb255(140,140,140)'
gleplot.get_color_palette(name='default')[source]

Get a preset color palette.

Parameters:

name (str)

Return type:

list

gleplot.get_gle_marker(matplotlib_marker, default='FCIRCLE', fill='full')[source]

Convert matplotlib marker to GLE marker name.

Parameters:
  • matplotlib_marker (str) – Matplotlib marker symbol ('o', 's', …) or a literal GLE marker name ('wcircle', 'FDIAMOND', …), which is passed through after validation against GLE’s own marker table.

  • default (str) – GLE marker used when the symbol is not recognized. Unrecognized symbols also emit a UserWarning – gleplot used to fall back silently, which turned a typo into a wrong-shaped marker with no indication anything had happened.

  • fill ({'full', 'none', 'white'}) – Fill style. 'full' returns the historical mapping verbatim; 'none' returns the transparent-outline family member and 'white' the opaque white-filled one (shapes with no fill variant, e.g. PLUS, are unaffected).

Returns:

GLE marker name, or None when no marker was requested.

Return type:

str or None

Raises:

ValueError – If fill is not one of MARKER_FILLS.

Warns:

UserWarning – If the marker symbol is neither a known matplotlib code nor a valid GLE marker name.

gleplot.mathtext_to_gle(s: str) → str[source]
gleplot.mathtext_to_gle(s: None) → None

Translate matplotlib mathtext ($...$) in s into GLE text markup.

Parameters:

s (str or None) – A display string as a matplotlib user would write it. Non-strings (including None) are returned unchanged, so callers may pass an optional label straight through.

Returns:

The string with every $...$ math segment rewritten in GLE markup and every non-math segment escaped so it renders literally (see escape_gle_text()). Returned unchanged when the unescaped $ count is odd (matplotlib would error; we degrade gracefully rather than guess what was meant).

Return type:

str or None

gleplot.validate_tick_format(fmt)[source]

Light validation of a GLE number-format string; returns it stripped.

Used by Axes.set_tick_format() and available to callers building a format string interactively (GLEstudio’s format preset builder). The check is deliberately weak, because GLE’s own parser is: gleplot.parser.tables.NUMBER_FORMAT_KEYWORDS documents that an unrecognized specifier is skipped with a printed note, not an error. So this only rules out the strings that could not possibly be a format – empty, multi-line, or not starting with a keyword GLE knows – and lets everything else (including arguments this version has never seen) through unchanged.

Parameters:

fmt (str) – Candidate format string, e.g. "fix 1" or "sci 2 10 expsign".

Returns:

fmt with surrounding whitespace removed.

Return type:

str

Raises:

ValueError – If fmt is not a string, is blank, spans multiple lines, or does not begin with a GLE number-format keyword.