API Reference

Module: gleplot

gleplot - Matplotlib-like plotting library for GLE

A Python library for creating scientific plots using matplotlib-like syntax that compiles directly to GLE (Graphics Layout Engine) format for publication- quality vector graphics.

Features

  • Matplotlib-compatible API (plot, scatter, bar, fill_between, errorbar)

  • Text annotations in data coordinates (text)

  • 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

Core Classes

Figure

class gleplot.Figure(figsize=(8, 6), dpi=100, style=None, graph=None, marker=None, sharex=False, sharey=False, data_prefix=None, height_ratios=None, width_ratios=None)[source]

Matplotlib-like figure for GLE plotting.

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, a COPY of style is taken at construction time – see the “Global defaults are copied, not shared” note below. An explicitly passed style is stored by reference, as before.

  • graph (GLEGraphConfig, optional) – Graph configuration. If None, a COPY of graph is taken at construction time (same note). An explicitly passed graph is stored by reference, as before.

  • marker (GLEMarkerConfig, optional) – Marker configuration. If None, a COPY of marker is taken at construction time (same note). An explicitly passed marker is stored by reference, as before.

  • sharex (bool)

  • sharey (bool)

  • data_prefix (str | None)

  • height_ratios (Sequence[float] | None)

  • width_ratios (Sequence[float] | None)

Notes

Global defaults are copied, not shared. GlobalConfig.style/ .graph/.marker are process-wide singletons. Setting GlobalConfig.style.font = 'helvetica' before creating a figure still changes that figure’s default font, exactly as documented in gleplot.config.GlobalConfig. But once a Figure exists, its style/graph/marker_config are independent objects (when no explicit config was passed in): editing fig.style.font in place (or reassigning fig.style) affects only fig – it can neither leak into other figures created earlier or later in the same process, nor mutate GlobalConfig itself. This is copy-AT-CONSTRUCTION semantics, the same rule matplotlib’s rcParams snapshot follows for a new Figure/Axes.

This only applies to the default, taken from GlobalConfig. A style/graph/marker object YOU pass in explicitly is still stored by reference, unchanged from before this note was added: two figures built with the same explicit config object still share it, and the object stays live for code that wants to mutate it after construction (gleplot.parser.recognizer does exactly this while reconstructing a Figure from parsed GLE text).

property source_warnings: List

Series skipped by the most recent GLE generation, and why.

A list of gleplot.sources.DanglingSourceRef – inspectable objects naming the series (axes index, series list, index, label) and the reference that could not be resolved (table id, column keys, reason). Empty for any figure whose series are all inline, which is every figure the scripting API builds.

Reset at the start of each generation, so it always describes the latest savefig/savefig_gle rather than accumulating.

property preview_decimation_report: List

Series the most recent generation actually decimated, and by how much.

A list of gleplot.writer.DecimationRecord (dataset name, label, factor, original point count) – empty unless that generation call passed preview_decimation=N (N > 1) AND at least one eligible series (line/scatter – see gleplot.writer.GLEWriter._deresolve_clause() for the full kind/ threshold rule) met gleplot.writer.GLEWriter.MIN_DERESOLVE_POINTS. Always [] for a generation that did not pass the argument at all, matching the DEFAULT emission being byte-identical to a build before G7 existed.

Reset at the start of each generation (mirrors source_warnings), so it always describes the latest savefig/savefig_gle rather than accumulating. Intended consumer: GLEstudio’s render controller, to show a “preview decimated x N” badge on the series it names and to keep hit-testing locked to the same decimated point set (SPEC §7.1).

subplots_adjust(*, left=None, right=None, bottom=None, top=None, wspace=None, hspace=None)[source]

Store subplot layout overrides (matplotlib-compatible API).

Parameters are normalized figure fractions except wspace/hspace, which follow matplotlib semantics (fraction of average subplot width/height).

Parameters:
Return type:

None

add_subplot(*args)[source]

Add subplot to figure.

Parameters:

*args (int) – Subplot specification (rows, cols, index) or single int E.g., add_subplot(2, 2, 1) or add_subplot(221)

Returns:

New axes object

Return type:

Axes

add_broken_xaxes(xlims, **kwargs)[source]

Add a panel whose x-axis is broken into adjacent segments.

The segments share one y-axis: tick labels and the y title appear only on the leftmost one, the sides that face each other are switched off, and the seam is marked with a rule or double-slash break marks. Series are declared once on the returned object and fanned out to every segment, sharing a single data sidecar; GLE clips each dataset to its own segment’s range.

Parameters:
  • xlims (sequence of (float, float)) – One (xmin, xmax) per segment, left to right; at least two.

  • **kwargs – Passed to gleplot.brokenaxes.BrokenAxeswidth_ratios, position, gap, divider, divider_color, divider_linewidth, divider_lstyle, break_mark_size, trim_seam_labels, xlabel_dist, title_dist.

Return type:

BrokenAxes

Notes

Plot through the returned object, not through the figure: this sets the figure’s current axes to the leftmost segment, so a subsequent fig.plot(...) / gca() would reach only that one segment.

Examples

>>> fig = glp.figure(figsize=(3.4, 2.6))
>>> bax = fig.add_broken_xaxes([(0, 0.02), (0.02, 3)],
...                            width_ratios=[1, 3], divider='slash')
>>> bax.errorbar(t, a, yerr=e, marker='o', fmt='none')
>>> bax.set_xlabel('t (us)')
>>> bax.set_ylabel('Asymmetry (%)')
gca()[source]

Get current axes (or create if needed).

Return type:

Axes

plot(x, y, **kwargs)[source]

Plot on current axes.

scatter(x, y, **kwargs)[source]

Scatter on current axes.

bar(x, height, **kwargs)[source]

Bar chart on current axes.

fill_between(x, y1, y2, **kwargs)[source]

Fill between on current axes.

errorbar(x, y, **kwargs)[source]

Error bar plot on current axes.

text(x, y, s, **kwargs)[source]

Add text on current axes.

axvline(x=0.0, **kwargs)[source]

Vertical reference line on current axes.

axhline(y=0.0, **kwargs)[source]

Horizontal reference line on current axes.

axvspan(xmin, xmax, **kwargs)[source]

Shaded vertical band on current axes.

axhspan(ymin, ymax, **kwargs)[source]

Shaded horizontal band on current axes.

imshow(Z, **kwargs)[source]

Display gridded data as a heatmap on current axes.

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

Draw contour lines on current axes.

tripcolor(x, y, z, **kwargs)[source]

Scattered-data heatmap on current axes.

tricontour(x, y, z, **kwargs)[source]

Scattered-data contour lines on current axes.

colorbar(label=None, format='fix 1', nticks=None, width=0.5, sep=0.3)[source]

Attach a vertical colorbar to the figure’s single heatmap axes.

Parameters:
  • label (str, optional) – Colorbar axis label (rotated text to the right of the bar).

  • format (str) – GLE format$ string for the tick labels (e.g. 'fix 1').

  • nticks (int, optional) – Approximate number of tick intervals. Default: 5.

  • width (float) – Colorbar width in cm.

  • sep (float) – Gap (cm) between the graph’s right edge and the colorbar.

Returns:

The stored colorbar dict (also attached to the heatmap under 'colorbar').

Return type:

dict

Raises:

ValueError – If no axes has a heatmap, if more than one does (ambiguous), or if the heatmap has neither z data nor explicit vmin/vmax to derive a colour range from and no reference to resolve one from later.

Notes

Reference-backed heatmaps (SPEC 14.5). A heatmap whose numbers come from a GridRef has no arrays here – they arrive per write from the provider. Rather than read arrays it does not have, the colorbar records an auto range and each write computes zmin/zmax/zstep from the data that write resolved, so a table edit re-flows into the bar instead of leaving a range baked at colorbar() time. Explicit vmin/vmax on the heatmap short-circuit that and are used as-is, here and at write time alike.

xlabel(label)[source]

Set x label on current axes.

Parameters:

label (str)

ylabel(label, axis='y')[source]

Set y label on current axes.

Parameters:
  • label (str) – Axis label text

  • axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right)

title(label)[source]

Set title on current axes.

Parameters:

label (str)

legend(**kwargs)[source]

Add legend to current axes.

absolutize_file_references(base_dir)[source]

Rewrite relative reference-mode data paths to absolute paths.

Reference-mode series (file_series) carry their data_file verbatim into the generated data command, so a relative path is only valid when GLE runs in the directory the reference is relative to. Call this on a figure whose script will be generated or compiled SOMEWHERE ELSE: the live preview’s temp session dir, an export to a different directory, or Save As across directories. Import-mode series regenerate their sidecars next to the script and are untouched. Paths are emitted in POSIX form (GLE accepts forward slashes on Windows); the writer quotes names containing spaces.

Return type:

None

savefig_gle(filepath, data_provider=None, preview_decimation=None, **kwargs)[source]

Save figure as GLE script.

Parameters:
  • filepath (str) – Output file path

  • data_provider (DataProvider, optional) – Resolver for series whose data_source references a table (see savefig() and gleplot.sources).

  • preview_decimation (DecimationPolicy, optional) – Preview-only deresolve factor (SPEC §6.1/§10.7). None (the default) emits byte-identically to a build before this option existed. A single int applies one factor to every eligible series (unchanged, byte-for-byte, since G7); a Mapping keyed by series label or a per-series Callable[[DecimationCandidate], Optional[int]] instead let a mixed figure (e.g. a 1k-point curve alongside a 500k-point trace) give each series its own factor – see gleplot.writer.DecimationPolicy for the full contract. When a resolved factor is given and > 1, large line/scatter series (see gleplot.writer.GLEWriter.MIN_DERESOLVE_POINTS) get a `` deresolve N`` clause on their dN line – GLE then draws (and this call’s caller may hit-test against) 1-in-N points instead of the full series, while axis autoscale is still computed from the full, undecimated data. A generation-time argument only: never stored on the figure, so to_dict/ from_dict and a saved .gle are unaffected – pass it only when writing a throwaway preview copy, never the document being saved. See preview_decimation_report for what got decimated.

  • folder (bool, optional) – If True, place the .gle script and generated data files in a sibling <name>.gleplot directory.

  • **kwargs – Additional options

Returns:

Path to created GLE file

Return type:

Path

savefig(filepath, format=None, dpi=None, data_provider=None, cairo=None, keep_intermediates=False, preview_decimation=None, **kwargs)[source]

Save figure as GLE script and/or compiled output.

Parameters:
  • filepath (str) – Output file path

  • format ({'pdf', 'png', 'eps', 'jpg', 'svg'}, optional) – Output format. If None, the format is auto-detected from the file suffix (.jpeg maps to jpg); an unrecognized or missing suffix defaults to saving the .gle script only. If format is given but the file extension differs, format wins.

  • dpi (int, optional) – DPI for raster formats

  • cairo (bool, optional) –

    Whether to compile with GLE’s -cairo device flag (SPEC §6.1/§10.6). None (the default) auto-detects via requires_cairo() – on for any figure using semi- transparency, off otherwise, so an ordinary opaque figure’s compile behaviour (and its written .gle text – the flag is compile-time only, never script-time) is completely unchanged. Pass True/False to force the flag either way. Ignored when format is 'gle' (no compile happens).

    When Cairo ends up active (auto or forced) and this figure’s configured font (style’s font) is not one of GLE’s Cairo-safe fonts, a UserWarning is raised: GLE itself substitutes a Cairo-safe font in that case (see gleplot.cairo_support), and SPEC’s “no silent drops” rule means that substitution must never happen without gleplot saying so.

  • data_provider (DataProvider, optional) –

    Supplies the tables that ColumnRef/GridRef series reference (gleplot.sources). Injected here, at write time, rather than held on the figure: the figure is a serializable document that to_dict round-trips and the provider is a live application object, so binding the two would make snapshots either lossy or impossible – and passing it per write is what lets one figure be rendered against different tables (a preview vs an export, a what-if dataset). Figures whose series are all inline (everything the scripting API builds) ignore it entirely.

    References that cannot be resolved do not raise: the affected series is skipped and recorded in source_warnings.

  • keep_intermediates (bool, optional) – If True, skip the post-compile cleanup of GLE-generated contour/ fitz intermediates (-cdata.dat/-clabels.dat/ -cvalues.dat, and a points-sourced heatmap/contour’s generated .z) that a compiled export otherwise removes from export_dir afterwards – see the “Engine intermediates” note below. Default False. Has no effect when this figure has no contour/heatmap series, or when format == 'gle' (no compile runs, so nothing was generated to clean up).

  • preview_decimation (DecimationPolicy, optional) – Preview-only deresolve factor – see savefig_gle() for the full contract. Generation-time only, never stored on the figure. Compiling with this set still produces a real format output (PDF/PNG/…), just from a decimated preview script – pass it for a live-preview compile, not for a save the user will treat as their document.

  • folder (bool, optional) – If True, place the exported file, the intermediate .gle script, and generated data files in a sibling <name>.gleplot directory.

  • **kwargs – Additional arguments

Returns:

Path to output file (GLE script or compiled output)

Return type:

Path

Notes

Engine intermediates (GLEstudio SPEC 9.1/10.8). Compiling a figure with a contour or a points-sourced (fitz) heatmap/contour makes the gle binary itself write extra files into export_dir as an undocumented side effect – <stem>-cdata.dat, <stem>-clabels.dat, <stem>-cvalues.dat, and (points-sourced only) the generated <stem>.z. These are never gleplot’s own output, so on a successful compile (format != 'gle') they are deleted from export_dir afterwards by exact name – never by glob or prefix match, so a user’s own file can only be caught if its name is a byte-for-byte match to one GLE itself would have written for this figure (see gleplot.compiler.remove_generated_intermediates()). Pass keep_intermediates=True to leave them in place, e.g. to inspect a contour’s raw crossings while debugging. A failed compile raises before cleanup runs, so its intermediates (if any were written) are never removed – they may help diagnose the failure.

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

Display the figure inline (in Jupyter notebooks) or save to a temporary file.

This method renders the figure to an image format and displays it if running in a Jupyter notebook or IPython environment. Otherwise, it saves to a temporary file and returns the path.

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

Raises:

RuntimeError – If GLE compiler is not available.

Examples

>>> import gleplot as glp
>>> fig = glp.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot([1, 2, 3], [1, 4, 9])
>>> fig.view()  # Display in notebook

Notes

Requires GLE to be installed for compilation. In non-Jupyter environments, saves to a temporary file instead.

to_dict()[source]

Serialize the figure to a JSON-safe project dictionary.

Produces the full, lossless object-model representation used by the project-file format and (later) undo/redo snapshots. The result is a top-level envelope:

{
    "format": "gleplot-project",
    "version": 1,
    "gleplot_version": <installed gleplot version>,
    "figure": { ... }
}

The figure block captures figure-level parameters (figsize, dpi, sharex, sharey, data_prefix), the data-file naming state, subplot layout overrides, unrecognized-content passthrough buckets (passthrough_header, passthrough_trailer) and metadata-block passthrough (metadata_extra), the per-figure style / graph / marker configuration overrides (serialized via each config’s own to_dict), and every axes with all of its series and state (including its own passthrough bucket) via Axes.to_dict().

Only authoritative state is serialized. Axis limits are serialized as they currently sit on each axes: limits explicitly set by the user are captured, while limits left unset remain None and are re-derived from data at GLE-generation time – keeping the format independent of that (order-dependent, potentially expensive) derivation. Calling to_dict twice on an unchanged figure yields an identical dict.

The generated-series data_file names and the figure’s set of used data-file names are round-tripped exactly, so regenerated GLE does not depend on the module-global data-file counter. The counter’s current value is nonetheless also saved (global_data_counter) so that continued plotting after from_dict() in a fresh process picks up where the original session left off instead of restarting at 0 and colliding with (or duplicating) previously used data_N.dat names. The contour/heatmap/fitz sidecar counters get the same treatment (sidecar_counters for a figure with a custom data_prefix, global_sidecar_counters for the shared default-prefix counter – see axes._reserve_sidecar), so a figure reloaded via from_dict() and then given a new contour/heatmap series keeps numbering forward rather than restarting at 1.

Returns:

JSON-serializable project dictionary.

Return type:

dict

requires_cairo()[source]

Whether rendering this figure needs GLE’s -cairo device flag.

True whenever the figure uses semi-transparency anywhere it can appear – a fill_between/axvspan/axhspan with alpha < 1 (Axes.fill_between(), Axes.axvspan(), Axes.axhspan()), or any colour expressed directly as rgba(...)/rgba255(...). See gleplot.cairo_support.figure_requires_cairo() for the exact rule and gleplot.compiler.build_compile_args() for where the answer turns into a compiler flag.

Built on to_dict() (per SPEC’s “render always works from a to_dict() snapshot” rule) rather than a live-model walk; axvspan/ axhspan declarations carry their alpha from the moment they’re created, so this sees them correctly even though their concrete x/y coordinates are only materialized later, at write time (Axes.materialize_spans()).

Return type:

bool

classmethod from_dict(d)[source]

Reconstruct an equivalent Figure from a project dict.

Parameters:

d (dict) – A project dictionary as produced by to_dict().

Returns:

A figure equivalent to the one that was serialized: round-tripping through to_dict() reproduces an equal dictionary and regenerated GLE (with the same data_prefix) is byte-identical.

Return type:

Figure

Raises:

ValueError – If the envelope format is missing/unrecognized or the version is unsupported.

Notes

Unknown keys inside the envelope, the figure block, and the config sub-dicts (style/graph/marker) are ignored for forward compatibility.

The module-global data-file counter (used to name auto-generated data_N.dat series when a figure has no custom data_prefix) is restored to max(current in-process value, saved value). Taking the max means that in a fresh process this simply continues the saved sequence, while in a long-running process with other figures already using the counter, it never rewinds and risks a future collision.

close()[source]

Close figure.

Axes

class gleplot.Axes(figure, position=None)[source]

Matplotlib-like axes for plotting.

Parameters:

position (Tuple[int, int, int])

axes_id: str

Stable opaque identity for this axes (GLEstudio SPEC 6.2/10.5): a uuid4 hex string assigned once at construction and never recomputed from position/content, so it survives to_dict/ from_dict round-trips and axes reordering. Deliberately NOT emitted into GLE output (writer.py never reads this attribute) – it lives only in the dict/project layer, where GLEstudio keys its calibration records and last-good-calibration store by it instead of by positional index (see gui/preview.py’s calibration injection and gui/geometry.py’s AxesCalibration). A parsed .gle file has no id to recover, so the recognizer’s freshly constructed Axes objects simply get a new one here, same as any other new Axes.

legend_offset: Tuple[float, float] | None

(dx_cm, dy_cm) or None (= the figure graph config’s legend_offset_x/legend_offset_y, themselves 0, 0 by default, i.e. no offset clause at all).

xformat: str | None

Tick-label number format per axis – GLE xaxis format "<fmt>" (see set_tick_format() for the syntax and validation).

xgrid_lstyle: int | None

Grid line style, width (points) and colour. Emitted as xticks lstyle/lwidth/color and, when the grid covers subticks, the matching xsubticks clause – in GLE the grid lines ARE the ticks, so these style the ticks too. Only written when the corresponding grid is on; a style with no grid would be a silent no-op.

xlabel_size: float | None

Axis-title styling – the xtitle/ytitle/y2title text is xlabel_text/… above; these are its hei/color/dist options. *_dist is the gap between the title and the tick labels (None = the figure graph config’s xlabel_distance / ylabel_distance, themselves None = GLE’s atitledist).

xticklabel_size: float | None

xlabels hei/color plus xaxis angle (which rotates the tick labels, not the axis).

Type:

Tick-label styling

y2ticklabel_size: float | None

y2 tick labels are OFF in GLE unless y2labels on is given, so setting any y2 tick-label property (including y2format) also turns them on – otherwise the property would be inert. See GLEWriter.add_axes().

title_size: float | None

Graph-title styling (GLE title "..." hei/color/dist). GLE’s title belongs to the graph block, so it lives here, per axes, rather than on the figure. title_dist None = the figure graph config’s title_distance (itself None = GLE’s default).

plot(x, y, linestyle='-', color=None, marker=None, markersize=6, linewidth=1, label=None, yaxis='y', offset=0.0, fillstyle=None, markerfacecolor=None, zorder=None, **kwargs)[source]

Plot line or scatter plot (if marker without line).

Parameters:
  • x (array-like) – Data coordinates

  • y (array-like) – Data coordinates

  • linestyle (str) – Line style (‘-’, ‘–’, ‘:’, ‘-.’)

  • color (str, optional) – Color name or code (‘b’, ‘red’, etc.)

  • marker (str, optional) – Marker symbol (‘o’, ‘s’, ‘^’, etc.) - omit for line only

  • markersize (float) – Marker size (matplotlib convention, 1-100)

  • linewidth (float) – Line width

  • label (str, optional) – Legend label

  • yaxis (str, optional) – Which y-axis to use: ‘y’ (left, default) or ‘y2’ (right)

  • fillstyle ({'full', 'none'}, optional) – 'none' draws an open (outline) marker instead of a filled one.

  • markerfacecolor (str, optional) – 'none' is equivalent to fillstyle='none'; 'white' gives an outline marker with an opaque white interior. Also accepted as the matplotlib alias mfc.

  • zorder (float, optional) – Draw order relative to other data series on the same axes. Higher values are drawn on top. When omitted, lines and scatters keep gleplot’s default layer (lines below scatters and error bars).

  • **kwargs – Additional matplotlib-compatible arguments

  • offset (float)

Returns:

Line object (for compatibility)

Return type:

Line2D

errorbar(x, y, yerr=None, xerr=None, fmt='-', color=None, marker=None, markersize=6, linewidth=1, label=None, capsize=None, capsize_cm=None, yaxis='y', offset=0.0, fillstyle=None, markerfacecolor=None, zorder=None, **kwargs)[source]

Plot data with error bars.

Parameters:
  • x (array-like) – Data coordinates

  • y (array-like) – Data coordinates

  • yerr (scalar, array-like, or tuple of (lower, upper), optional) – Vertical error bar sizes. Can be: - scalar: constant symmetric error for all points - 1D array: per-point symmetric error - tuple (lower, upper): per-point asymmetric error bars

  • xerr (scalar, array-like, or tuple of (left, right), optional) – Horizontal error bar sizes. Same format as yerr.

  • fmt (str) – Format string for the line/marker (e.g., ‘-o’, ‘–s’, ‘none’)

  • color (str, optional) – Color name or code

  • marker (str, optional) – Marker symbol (‘o’, ‘s’, ‘^’, etc.)

  • markersize (float) – Marker size (matplotlib convention, 1-100)

  • linewidth (float) – Line width

  • label (str, optional) – Legend label

  • capsize (float, optional) – Width of error bar caps in matplotlib points (typical: 3-5). Automatically converted to GLE cm units via parser.units.capsize_pt_to_cm. Default: None (no caps)

  • capsize_cm (float, optional) – Width of error bar caps directly in GLE cm units (typical: 0.05-0.15). If specified, this overrides capsize. Use this for direct control.

  • yaxis (str, optional) – Which y-axis to use: ‘y’ (left, default) or ‘y2’ (right)

  • fillstyle ({'full', 'none'}, optional) – 'none' draws an open (outline) marker instead of a filled one.

  • markerfacecolor (str, optional) – 'none' is equivalent to fillstyle='none'; 'white' gives an outline marker with an opaque white interior. Also accepted as the matplotlib alias mfc.

  • zorder (float, optional) – Draw order relative to other data series on the same axes. Higher values are drawn on top. When omitted, error bars sit above lines and scatters (the historical gleplot default).

  • **kwargs – Additional arguments

  • offset (float)

Return type:

self

Examples

Symmetric vertical error bars:

>>> ax.errorbar(x, y, yerr=0.5)

Asymmetric vertical error bars:

>>> ax.errorbar(x, y, yerr=([0.2, 0.3], [0.5, 0.4]))

Both vertical and horizontal error bars:

>>> ax.errorbar(x, y, yerr=0.5, xerr=0.3)
errorbar_from_file(data_file, x_col, y_col, yerr_col=None, color=None, marker='o', markersize=6, label=None, capsize=None, yaxis='y', fillstyle=None, markerfacecolor=None, **kwargs)[source]

Plot by referencing columns in an existing external data file.

This avoids writing generated data_*.dat files. Column indices are 1-based to match GLE conventions.

fillstyle='none' / markerfacecolor='none' (alias mfc) select an open marker; markerfacecolor='white' selects a white-filled one.

Parameters:
  • data_file (str)

  • x_col (int)

  • y_col (int)

  • yerr_col (int | None)

  • color (str | None)

  • marker (str | None)

  • markersize (float)

  • label (str | None)

  • capsize (float | None)

  • yaxis (str)

  • fillstyle (str | None)

  • markerfacecolor (str | None)

line_from_file(data_file, x_col, y_col, color=None, linestyle='-', linewidth=1, label=None, yaxis='y')[source]

Plot a line by referencing columns in an external data file.

This avoids creating generated data_*.dat files for overlay lines. Column indices are 1-based to match GLE conventions.

Parameters:
SCATTER_DEFAULT_S = 20

Default scatter size, in matplotlib’s points**2.

scatter(x, y, color=None, s=None, marker='o', label=None, yaxis='y', markersize=None, fillstyle=None, markerfacecolor=None, zorder=None, **kwargs)[source]

Create scatter plot.

Accepts either sizing convention:

  • s – matplotlib’s scatter size, an area in points**2 (matplotlib’s own default is ~36; gleplot’s is 20). Converted to a marker size with the square-root relation matplotlib defines between the two, markersize = sqrt(s), times gleplot’s 1.2 visibility factor, and from there to GLE’s msize the same way plot() does it.

  • markersize – a diameter in points, matplotlib’s Line2D convention and exactly what plot() takes. Used as given, with no area conversion, so a scatter and a plot asking for the same markersize draw the same size of marker.

Passing neither uses s = 20. Passing both is ambiguous and ``markersize`` wins – it is a size, not an area, so honouring it needs no conversion and leaves nothing to guess.

Parameters:
  • x (array-like) – Data coordinates

  • y (array-like) – Data coordinates

  • color (str, optional) – Point color

  • s (float, optional) – Marker area in points**2 (matplotlib scatter convention). Default 20 when neither s nor markersize is given. A per-point array is not supported: GLE’s msize is a per-dataset attribute, so one series draws one marker size.

  • marker (str) – Marker symbol

  • label (str, optional) – Legend label

  • yaxis (str, optional) – Which y-axis to use: ‘y’ (left, default) or ‘y2’ (right)

  • markersize (float, optional) – Marker diameter in points (matplotlib Line2D/plot() convention). Takes precedence over s.

  • fillstyle ({'full', 'none'}, optional) – 'none' draws open (outline) markers instead of filled ones.

  • markerfacecolor (str, optional) – 'none' is equivalent to fillstyle='none'; 'white' gives outline markers with an opaque white interior. Also accepted as the matplotlib alias mfc.

  • zorder (float, optional) – Draw order relative to other data series on the same axes. Higher values are drawn on top.

  • **kwargs – Additional arguments

Return type:

self

bar(x, height, color=None, label=None, zorder=None, width=None, **kwargs)[source]

Create bar chart.

Note: Due to GLE limitations, all bars in a chart use the same color. If a list of colors is provided, only the first color is used.

Parameters:
  • x (array-like) – Bar positions or categories

  • height (array-like) – Bar heights

  • color (str or list of str, optional) – Bar color. If a list is provided, only the first color is used due to GLE limitations. Default is ‘red’.

  • label (str, optional) – Legend label (currently not supported by GLE for bar charts)

  • width (float, optional) – Bar width in DATA units (G19), GLE’s bar dN ... width w. The default, None, is the engine’s own behaviour and gleplot’s historical one: GLE sizes the set from the data, taking half the smallest gap between consecutive x values. Deliberately not matplotlib’s constant 0.8 default – every bar chart written before this parameter existed must keep emitting the script it emits now. Note also that width is a keyword here where matplotlib’s is positional: this method’s third positional parameter has always been color.

  • **kwargs – Additional arguments

  • zorder (float | None)

Return type:

self

Examples

>>> fig = glp.figure()
>>> ax = fig.add_subplot(111)
>>> categories = np.array([1, 2, 3, 4, 5])
>>> values = np.array([10, 24, 36, 18, 7])
>>> ax.bar(categories, values, color='blue')
>>> fig.savefig('bar_chart.pdf')
fill_between(x, y1, y2, color=None, alpha=1.0, label=None, offset=0.0, **kwargs)[source]

Fill area between two curves.

Parameters:
  • x (array-like) – x coordinates

  • y1 (array-like) – Two y series

  • y2 (array-like) – Two y series

  • color (str, optional) – Fill color

  • alpha (float) – Transparency (0-1). Default 1.0 (opaque), matching matplotlib’s fill_between and keeping every pre-Cairo-support figure’s .gle output byte-identical unless a caller actually asks for transparency. Below 1.0, the fill is genuinely semi-transparent (gleplot.colors.apply_alpha composes an rgba255(...) colour) and rendering it requires GLE’s Cairo device, which gleplot’s compile pipeline enables automatically – see gleplot.figure.Figure.requires_cairo() and SPEC §6.1/§10.6.

  • label (str, optional) – Legend label

  • **kwargs – Additional arguments

  • offset (float)

Return type:

self

axvline(x=0.0, ymin=0.0, ymax=1.0, color=None, linestyle='-', linewidth=1, label=None, **kwargs)[source]

Draw a vertical reference line at data coordinate x.

Parameters:
  • x (float) – Position of the line, in data coordinates.

  • ymin (float) – Vertical extent as a fraction of the axes height (matplotlib semantics): 0 is the bottom of the axes, 1 the top.

  • ymax (float) – Vertical extent as a fraction of the axes height (matplotlib semantics): 0 is the bottom of the axes, 1 the top.

  • color (str, optional) – Line colour. Default: black.

  • linestyle (str) – '-', '--', ':' or '-.'.

  • linewidth (float) – Line width in points.

  • label (str, optional) – Legend label.

Returns:

The stored declaration (also appended to self.reflines).

Return type:

dict

Notes

The line is realized as a two-point dataset whose end points are computed when the figure is written, so it tracks any axis limits set afterwards. It is drawn underneath the data series.

axhline(y=0.0, xmin=0.0, xmax=1.0, color=None, linestyle='-', linewidth=1, label=None, **kwargs)[source]

Draw a horizontal reference line at data coordinate y.

xmin/xmax are the horizontal extent as a fraction of the axes width (matplotlib semantics). See axvline() for the rest.

Parameters:
axvspan(xmin, xmax, ymin=0.0, ymax=1.0, color=None, alpha=1.0, label=None, **kwargs)[source]

Shade the vertical band between data coordinates xmin and xmax.

Parameters:
  • xmin (float) – Band edges, in data coordinates.

  • xmax (float) – Band edges, in data coordinates.

  • ymin (float) – Vertical extent as a fraction of the axes height (matplotlib semantics).

  • ymax (float) – Vertical extent as a fraction of the axes height (matplotlib semantics).

  • color (str, optional) – Fill colour. Default: light gray.

  • alpha (float) – Transparency (0-1). Default 1.0 (opaque), matching matplotlib and keeping every pre-Cairo-support figure’s .gle output byte-identical unless a caller actually asks for transparency. Below 1.0, the band is genuinely semi-transparent (gleplot.colors.apply_alpha composes an rgba255(...) colour, exactly as fill_between() does – spans are materialized into fills at write time) and rendering it requires GLE’s Cairo device, which gleplot’s compile pipeline enables automatically – see gleplot.figure.Figure.requires_cairo() and SPEC §6.1/§10.6.

  • label (str, optional) – Legend label.

Returns:

The stored declaration (also appended to self.spans).

Return type:

dict

axhspan(ymin, ymax, xmin=0.0, xmax=1.0, color=None, alpha=1.0, label=None, **kwargs)[source]

Shade the horizontal band between data coordinates ymin and ymax.

xmin/xmax are the horizontal extent as a fraction of the axes width (matplotlib semantics). See axvspan() for the rest, including the alpha behaviour.

Parameters:
static guide_spanned_bounds(entry, limits)[source]

The (lo, hi) bounds of the axis entry spans, from limits.

A 'v' guide (axvline/axvspan) is positioned in x and spans y; a 'h' guide is the transpose.

classmethod guide_needs_engine_range(entry, limits)[source]

Whether this guide has to be drawn against GLE’s own range (G17).

True exactly when a bound of the axis the guide spans is None at write time – an axes with nothing to resolve that axis from (G14), or a range that collapsed and was handed back to the engine (G15). Such a guide cannot be materialized into a literal dataset without inventing the very range GLE has yet to choose, so it is emitted as a layered draw over xgmin/ygmax instead (gleplot.guides).

False – the overwhelmingly common case – keeps the historical two-point dataset emission untouched, byte for byte.

Return type:

bool

engine_range_guides(series_list, limits)[source]

The visible guides in series_list routed to the draw form.

Return type:

List[Series]

dataset_form_guides(series_list, limits)[source]

The visible guides in series_list that materialize into datasets.

The exact complement of engine_range_guides() among the visible entries – both filter on the same two predicates – and therefore positionally aligned, by construction, with what materialize_reflines() / materialize_spans() return for the same limits. That alignment is what lets the writer put each materialized dataset’s provenance marker (G18-lite) back beside the declaration it came from; Figure._write_axes_content checks the two lists are the same length rather than trusting it silently.

Return type:

List[Series]

materialize_reflines(limits)[source]

Turn self.reflines into concrete two-point line series.

Parameters:

limits (tuple) – (xmin, xmax, ymin, ymax) – the axis limits actually being written.

Returns:

  • list of dict – Line dicts in the same shape plot() produces, ready for GLEWriter.add_plot_line. Nothing is stored back on the axes, so writing a figure twice does not duplicate content.

  • Two kinds of guide materialize into nothing here (hidden ones)

  • (visible = False, SPEC 14.6), and – since G17 – ones whose

  • spanned axis has an unresolved bound. The latter are the figures the

  • literal dataset got wrong; they are emitted as draw calls instead

  • (see guide_needs_engine_range() and gleplot.guides), and

  • engine_range_guides() is how the writer collects them.

Return type:

List[LineSeries]

materialize_spans(limits)[source]

Turn self.spans into concrete fill-between series.

See materialize_reflines(); the same contract applies (nothing is stored back; hidden bands, and bands across an axis with an unresolved bound, materialize into nothing).

Return type:

List[FillSeries]

text(x, y, s, color=None, fontsize=None, ha='left', va='center', bbox=None, **kwargs)[source]

Add free-form text annotation in data coordinates.

Parameters:
  • x (float) – Data coordinates.

  • y (float) – Data coordinates.

  • s (str) – Text to render.

  • color (str, optional) – Text color.

  • fontsize (float, optional) – Font size in points.

  • ha (str, optional) – Horizontal alignment: ‘left’, ‘center’, or ‘right’.

  • va (str, optional) – Vertical alignment placeholder for API compatibility.

  • bbox (dict, optional) – Optional text box settings. Supported key: facecolor.

imshow(Z, extent=None, origin='lower', cmap=None, vmin=None, vmax=None, interpolation='bicubic', pixels=None, invert=False, label=None, **kwargs)[source]

Display gridded 2-D data Z as a colour map (heatmap).

Parameters:
  • Z (array-like, shape (ny, nx)) – Gridded scalar field.

  • extent (tuple, optional) – (xmin, xmax, ymin, ymax) mapping the grid onto data coordinates. Default (0, nx, 0, ny).

  • origin ({'lower', 'upper'}) – 'lower' (default) puts row 0 of Z at ymin (the scientific convention; note this differs from matplotlib’s 'upper' default). 'upper' flips the rows when writing the .z sidecar.

  • cmap (str, optional) – Palette name (see gleplot.palettes.SUPPORTED_CMAPS). When None, uses the figure graph config’s default_cmap.

  • vmin (float, optional) – Colour normalization range (GLE zmin/zmax). None uses GLE’s data-range default.

  • vmax (float, optional) – Colour normalization range (GLE zmin/zmax). None uses GLE’s data-range default.

  • interpolation ({'bicubic', 'nearest'}) – Sampling interpolation for the .z grid.

  • pixels (int or (px, py), optional) – Bitmap resolution. Default from graph config colormap_pixels.

  • invert (bool) – Invert the colour mapping.

  • label (str, optional) – Series label (not drawn by the colormap itself; kept for the GUI).

Returns:

The stored heatmap series dict.

Return type:

dict

contour(*args, levels=None, colors='black', linewidths=1.0, linestyles='-', clabel=False, clabel_fmt='fix 1', label=None, **kwargs)[source]

Draw contour lines of gridded data.

Signatures: contour(Z) or contour(x, y, Z) with 1-D x (nx), 1-D y (ny), 2-D Z (ny, nx). x/y must be uniformly spaced.

The matplotlib spelling contour(X, Y, Z) with 2-D X/Y from np.meshgrid is also accepted: the grid is checked for regularity (constant rows in X, constant columns in Y) and its 1-D axes extracted, since GLE’s .z grid is an extent plus a shape. A genuinely irregular grid raises – use tricontour() for scattered data.

Parameters:
  • levels (None, int, or sequence) – None uses GLE’s default 10 levels. An int n emits values from zmin to zmax step (zmax-zmin)/n. A sequence emits values v1 v2 ....

  • colors (str) – Contour line colour.

  • linewidths (float) – Line width (matplotlib points).

  • linestyles (str) – Line style (‘-’, ‘–’, ‘:’, ‘-.’).

  • clabel (bool) – Draw inline contour labels from the generated -clabels.dat.

  • clabel_fmt (str) – GLE format$ string for the labels.

  • label (str | None)

Returns:

The stored contour series dict.

Return type:

dict

tripcolor(x, y, z, gridsize=(50, 50), extent=None, cmap=None, vmin=None, vmax=None, interpolation='bicubic', pixels=None, invert=False, label=None, **kwargs)[source]

Heatmap from scattered (x, y, z) samples via GLE fitz gridding.

Writes a points sidecar (raw x y z triples) and emits a begin fitz block that grids the data (Akima interpolation) to a .z file at GLE compile time, then a colormap of that grid.

Parameters:
  • x (array-like) – Equal-length 1-D scattered samples.

  • y (array-like) – Equal-length 1-D scattered samples.

  • z (array-like) – Equal-length 1-D scattered samples.

  • gridsize ((nx, ny)) – Interpolation grid resolution.

  • extent (tuple, optional) – (xmin, xmax, ymin, ymax). Default: data bounds.

  • cmap (str | None)

  • vmin (float | None)

  • vmax (float | None)

  • interpolation (str)

  • invert (bool)

  • label (str | None)

:param (remaining kwargs as imshow()).:

tricontour(x, y, z, gridsize=(50, 50), extent=None, ncontour=3, levels=None, colors='black', linewidths=1.0, linestyles='-', clabel=False, clabel_fmt='fix 1', label=None, **kwargs)[source]

Contour lines from scattered (x, y, z) samples via GLE fitz.

Writes a points sidecar and emits a begin fitz block (gridding at compile time) followed by a begin contour block on the generated .z grid.

Parameters:
  • ncontour (int) – fitz neighbour-point count per interpolation node.

  • colors (str)

  • linewidths (float)

  • linestyles (str)

  • clabel (bool)

  • clabel_fmt (str)

  • label (str | None)

:param (remaining kwargs as contour()).:

set_xlabel(label)[source]

Set x-axis label.

Parameters:

label (str)

set_ylabel(label, axis='y')[source]

Set y-axis label.

Parameters:
  • label (str) – Axis label text

  • axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right)

set_title(label)[source]

Set subplot title.

Parameters:

label (str)

set_xscale(scale)[source]

Set x-axis scale (‘linear’ or ‘log’).

Parameters:

scale (str)

set_yscale(scale, axis='y')[source]

Set y-axis scale.

Parameters:
  • scale (str) – Scale type: ‘linear’ or ‘log’

  • axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right)

set_xlim(xmin, xmax)[source]

Set x-axis limits.

None puts that bound back on AUTO – derived from the data at GLE-generation time – which is what an editor’s “auto” checkbox means and what a freshly created axes carries.

Parameters:
set_ylim(ymin, ymax, axis='y')[source]

Set y-axis limits.

Parameters:
  • ymin (float or None) – Axis limits; None = auto (see set_xlim()).

  • ymax (float or None) – Axis limits; None = auto (see set_xlim()).

  • axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right)

set_xticks(ticks=None, labels=None, *, dticks=None, dsubticks=None)[source]

Control x-axis tick placement.

Parameters:
  • ticks (sequence of float, optional) – Explicit tick positions (GLE xplaces). Passing None leaves the current setting alone; pass an empty sequence to draw no labelled ticks at all.

  • labels (sequence of str, optional) – Tick labels (GLE xnames), one per entry of ticks.

  • dticks (float, optional) – Major tick interval (GLE dticks) – the usual way to keep two segments of a broken axis from colliding at the seam.

  • dsubticks (float, optional) – Minor tick interval (GLE dsubticks).

Return type:

self

set_yticks(ticks=None, labels=None, *, dticks=None, dsubticks=None)[source]

Control y-axis tick placement. See set_xticks().

Parameters:
legend(loc='best', **kwargs)[source]

Show a legend (GLE’s graph key).

Parameters:
  • loc (str) – matplotlib legend location. All eleven matplotlib strings map onto GLE’s nine key anchors ('best' is not computed – like matplotlib’s own 'best' fallback in ambiguous cases it means top right). GLE short forms ('tr', 'bl', …) are also accepted. An unrecognized value warns and uses top right.

  • fontsize (float or str, optional) – Legend text height, in matplotlib points, emitted as GLE’s key ... hei (the only lever on key size before this existed was the figure-wide style fontsize). matplotlib’s relative names ('small', 'x-large', …) are resolved against the figure’s style fontsize at call time.

  • frameon (bool, optional) – Draw the box around the key (default True, as matplotlib). False emits GLE’s key ... nobox.

  • ncol (int, optional) – Only a single column is expressible: GLE builds multi-column keys from separator commands in a standalone begin key block, which gleplot does not emit. 1 is accepted; anything else warns.

  • ncols (int, optional) – Only a single column is expressible: GLE builds multi-column keys from separator commands in a standalone begin key block, which gleplot does not emit. 1 is accepted; anything else warns.

  • **kwargs – Any other matplotlib legend keyword has no GLE key equivalent and warns rather than being silently dropped.

Return type:

self

grid(visible=None, which='major', axis='both', color=None, linestyle=None, linewidth=None, **kwargs)[source]

Turn the graph grid on or off, matplotlib-style.

GLE has no separate grid object: xaxis grid makes that axis’ ticks long enough to reach the opposite side, and the resulting lines ARE the grid (manual, “Graph Commands”: xaxis grid). Three consequences the model is honest about:

  • A grid always covers the main ticks. which='minor' alone is not expressible; it is normalized to 'both' with a warning rather than silently dropped.

  • which='both' adds xsubticks on, GLE’s “grid lines at each subtick” mode.

  • Grid style is tick style (xticks lstyle/lwidth/color), so it also restyles the ticks of that axis.

Parameters:
  • visible (bool, optional) – True/False to switch the grid on/off. None (the default) means “on” when any style argument is given, and otherwise TOGGLES the targeted axes, as matplotlib does.

  • which ({'major', 'minor', 'both'}) – Which ticks carry grid lines. 'minor' is normalized to 'both' (see above).

  • axis ({'both', 'x', 'y'}) – Which axis’ grid to change. x2/y2 have no grid of their own – they are where the x/y grid lines end.

  • color (str, optional) – Grid line colour (any gleplot.colors.rgb_to_gle() spelling).

  • linestyle (str or int, optional) – matplotlib line style ('-', '--', ':', '-.') or a raw GLE lstyle number.

  • linewidth (float, optional) – Grid line width in points.

Returns:

self, so calls can be chained (gleplot has always returned this; matplotlib returns None).

Return type:

Axes

Raises:

ValueError – On an unknown which/axis/linestyle value, a non-positive linewidth, or an unsupported keyword argument.

Examples

>>> ax.grid(True, which='both', linestyle=':', color='grey40')
set_tick_format(fmt, axis='both')[source]

Set the tick-label number format (GLE xaxis format "<fmt>").

fmt is a GLE format string – the same syntax as the format$() function (manual, “Programming”: format$): a base format (fix, sci, eng, round, percent, frac, pi, dec, hex, bin, append) with its arguments, optionally followed by modifiers (nozeroes, sign, pad, prefix, prepend, min, max) and optionally several formats combined, e.g. "sci 2 10 min 1e2 fix 0".

It is stored as a free-form string: GLE is the authority on the syntax and a friendly preset builder belongs in a GUI, not here. Validation is deliberately light – non-empty, single-line, and starting with a keyword GLE knows – so that format strings this version has never heard of still round-trip.

Parameters:
  • fmt (str or None) – The format string, or None to clear it (GLE’s automatic labelling).

  • axis ({'both', 'x', 'y', 'y2'}) – Which axis to apply it to. 'both' means x and y (not y2, which is a distinct axis with its own data range).

Returns:

self.

Return type:

Axes

Raises:

ValueError – On an unknown axis, or a format string that is empty, multi-line, or does not begin with a GLE format keyword.

Notes

GLE’s y2 (and x2) tick labels are off unless y2labels on is given, so setting axis='y2' also turns them on at write time – see gleplot.writer.GLEWriter.add_axes().

get_xlim()[source]

Get x-axis limits.

Either bound is None when it is on AUTO – to be derived from the data at GLE-generation time – which is how every figure starts out.

Return type:

Tuple[float | None, float | None]

get_ylim(axis='y')[source]

Get y-axis limits (None = auto, see get_xlim()).

Parameters:

axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right)

Return type:

Tuple[float | None, float | None]

has_plots()[source]

Check if axes has any plots.

Return type:

bool

has_y2_plots()[source]

Check if axes has any plots using the y2 axis.

Return type:

bool

to_dict()[source]

Serialize this axes to a JSON-safe dictionary.

Captures the subplot position, all axis/scale/limit/legend state, the shared-axes visibility flags, and every series list (lines, scatters, bars, fills, errorbars, file_series, texts) with their numeric data converted to plain Python lists. numpy arrays and scalars are converted so the result is directly json-safe and deterministic.

The data_file name stored on each generated series is preserved verbatim so that a round-trip produces byte-identical GLE regardless of the module-global data-file counter state.

Return type:

dict

classmethod from_dict(figure, d)[source]

Reconstruct an Axes from a to_dict() payload.

Parameters:
  • figure (Figure) – Parent figure the new axes is attached to.

  • d (dict) – Axes payload produced by to_dict(). Unknown keys are ignored for forward compatibility.

Return type:

Axes

:param Each series is rebuilt as its gleplot.series class: :param whose: :param ARRAY_FIELDS say which values are restored to float numpy: :param arrays; optional error arrays that were None stay None. All: :param style keys: :param labels and the data_file names are restored: :param verbatim: :param as are any keys the class does not declare (a project: :param written by a newer gleplot still round-trips).:

Configuration Classes

GLEStyleConfig

class gleplot.GLEStyleConfig(font='', fontsize=12, default_linewidth=1.5, default_color='BLUE', default_marker_color='BLUE', line_style_solid=1, line_style_dashed=3, line_style_dotted=2, line_style_dashdot=6)[source]

GLE rendering style configuration.

Parameters:
  • font (str)

  • fontsize (float)

  • default_linewidth (float)

  • default_color (str)

  • default_marker_color (str)

  • line_style_solid (int)

  • line_style_dashed (int)

  • line_style_dotted (int)

  • line_style_dashdot (int)

font

GLE font name (e.g., ‘times8’, ‘psagb’, ‘plti’). If None or empty string, uses GLE’s default font. Default: None

Type:

str or None

fontsize

Font size in points. Default: 12 (optimized for GLE/PDF readability)

Type:

float

default_linewidth

Default line width in points (unit: 1/72 inch). Default: 1.5 points ≈ 0.053 cm (increased for visibility in PDFs)

Type:

float

default_color

Colour used by gleplot.Axes.plot(), errorbar(), errorbar_from_file() and line_from_file() when the call passes no color. Any spelling gleplot.colors.rgb_to_gle() accepts. Default: ‘BLUE’ – the colour those methods hard-coded before this field was wired up, so the default changes nothing. (bar() and fill_between() keep their own distinct defaults, RED and LIGHTBLUE.)

Type:

str

default_marker_color

Same, for a marker-only series – what gleplot.Axes.scatter() produces, and plot() with a marker and no line. Default: ‘BLUE’

Type:

str

line_style_solid

GLE line style for solid lines. Default: 1

Type:

int

line_style_dashed

GLE line style for dashed lines (–). Default: 3

Type:

int

line_style_dotted

GLE line style for dotted lines (:). Default: 2

Type:

int

line_style_dashdot

GLE line style for dash-dot lines (-.). Default: 6

Type:

int

Notes

The line_style_* defaults are the GLE lstyle numbers that actually render as their names say, measured by compiling a ruler of set lstyle 1..9 strokes with GLE 4.3.10 and looking at the result:

lstyle

renders as

1

solid

2

dotted (dense)

3

dashed

4

dotted (sparse)

5

dashed (long)

6

dash-dot

7

dash-dot (sparse)

8

dash-dot (dense)

9

dashed (long, sparse)

gleplot previously defaulted to dashed=2 / dotted=3 / dashdot=4, i.e. linestyle='--' drew a dotted line and ':' drew a dashed one. Do not “restore” those numbers: they were transposed, and dashed-vs-dotted is load-bearing in publication figures where a dashed curve conventionally means a fit.

font: str = ''
fontsize: float = 12
default_linewidth: float = 1.5
default_color: str = 'BLUE'
default_marker_color: str = 'BLUE'
line_style_solid: int = 1
line_style_dashed: int = 3
line_style_dotted: int = 2
line_style_dashdot: int = 6
to_dict()[source]

Convert config to dictionary.

Return type:

Dict[str, Any]

GLEGraphConfig

class gleplot.GLEGraphConfig(scale_mode='auto', title_distance=None, xlabel_distance=None, ylabel_distance=None, legend_position='tr', legend_offset_x=0.0, legend_offset_y=0.0, smooth_curves=False, show_grid=False, default_cmap='viridis', colormap_pixels=200)[source]

GLE graph configuration.

Parameters:
  • scale_mode (str)

  • title_distance (float | None)

  • xlabel_distance (float | None)

  • ylabel_distance (float | None)

  • legend_position (str)

  • legend_offset_x (float)

  • legend_offset_y (float)

  • smooth_curves (bool)

  • show_grid (bool)

  • default_cmap (str)

  • colormap_pixels (int)

scale_mode

Graph scaling mode: ‘auto’ (auto-sizes and centers), ‘fixed’ (uses specified size), or ‘fullsize’ (axes fill entire box, no margins). Default: ‘auto’

Type:

str

title_distance

Figure-wide default for Axes.title_dist – the dist option of GLE’s title command, in cm. A per-axes title_dist wins over it. None (the default) emits no dist at all, leaving GLE’s own spacing.

Changed in version 2.4: Was an inert 0.1 that nothing read. It is now the default for the per-axes distance, and its default is None so that figures which never set it emit exactly the GLE they always did. A project serialized with the old inert 0.1 will, once reloaded, actually emit dist 0.1.

Type:

float or None

xlabel_distance

Same, for Axes.xlabel_dist – the dist option of GLE’s xtitle command (distance between the axis title and the tick labels), in cm. Default: None.

Type:

float or None

ylabel_distance

Same, for Axes.ylabel_dist (GLE ytitle ... dist) and, when the axes sets no distance of its own, Axes.y2label_dist (y2title ... dist). Default: None.

Type:

float or None

legend_position

Default legend position: ‘tl’, ‘tr’, ‘bl’, ‘br’, ‘tc’, ‘bc’, ‘lc’, ‘rc’, ‘cc’. Options: ‘top right’, ‘top left’, ‘bottom right’, ‘bottom left’, ‘center’. Default: ‘tr’ (top right)

Type:

str

legend_offset_x

Figure-wide default legend x-offset from its anchor (cm), used by every axes whose own legend_offset is None. Default: 0.0.

Type:

float

legend_offset_y

The y half of the same default (cm). Default: 0.0.

(0.0, 0.0) means “no offset”, and emits no offset clause – so the defaults leave GLE output unchanged.

Type:

float

smooth_curves

Draw line series as a fitted spline through the points (GLE’s smooth keyword) instead of as a polyline joining them. Opt-in: a smoothed curve is an interpolation, not the data, so it must never be applied without being asked for. Default: False

Type:

bool

show_grid

Figure-wide default grid: when True, every axes that has not called gleplot.Axes.grid() itself gets a main-tick grid on both axes (GLE xaxis grid / yaxis grid). An axes that HAS called grid() – including grid(False) – keeps its own answer. Default: False

Type:

bool

default_cmap

Default colour map used by imshow/tripcolor when cmap is not passed. One of the names in gleplot.palettes.SUPPORTED_CMAPS. Default: ‘viridis’

Type:

str

colormap_pixels

Default bitmap resolution (pixels per side) for colormap rendering when imshow(pixels=...) is not given. Default: 200

Type:

int

scale_mode: str = 'auto'
title_distance: float | None = None
xlabel_distance: float | None = None
ylabel_distance: float | None = None
legend_position: str = 'tr'
legend_offset_x: float = 0.0
legend_offset_y: float = 0.0
smooth_curves: bool = False
show_grid: bool = False
default_cmap: str = 'viridis'
colormap_pixels: int = 200
to_dict()[source]

Convert config to dictionary.

Return type:

Dict[str, Any]

GLEMarkerConfig

class gleplot.GLEMarkerConfig(default_marker='fcircle', msize_scale=1.0, mdist=None)[source]

Marker style configuration.

Parameters:
default_marker

Default marker type when creating scatter plots. Options: ‘circle’, ‘square’, ‘triangle’, ‘diamond’, ‘cross’, ‘fcircle’, ‘fsquare’, ‘ftriangle’, ‘fdiamond’ (filled variants). Default: ‘fcircle’ (filled circle)

Type:

str

msize_scale

Scaling factor for marker sizes. Multiplies the msize value. Default: 1.0

Type:

float

mdist

Default marker distance (space between markers on continuous lines). If None, markers appear at every point. Default: None

Type:

Optional[float]

default_marker: str = 'fcircle'
msize_scale: float = 1.0
mdist: float | None = None
to_dict()[source]

Convert config to dictionary.

Return type:

Dict[str, Any]

GlobalConfig

class gleplot.GlobalConfig[source]

Global gleplot configuration.

Provides singleton-like access to default configuration settings that apply to all new figures created.

Access style, graph, and marker configurations directly as class attributes:

Examples

>>> from gleplot.config import GlobalConfig
>>> # Change default font globally
>>> GlobalConfig.style.font = 'helvetica'
>>> # All new figures will use this font
>>> # Or reset to defaults
>>> GlobalConfig.reset()

Notes

Copy-at-construction, not shared-by-reference. GlobalConfig.style (and .graph, .marker) really is one shared, mutable instance – editing it here, before any figure exists, is exactly how you change the default for every figure created afterwards. But gleplot.figure.Figure and gleplot.writer.GLEWriter each take an independent COPY of the current value at construction time (when their own style/ graph/marker argument is omitted), not a reference to this singleton. So:

  • GlobalConfig.style.font = 'x' then fig = Figure()fig gets 'x' (the default was read at construction time).

  • fig = Figure() then fig.style.font = 'x' – only fig changes; GlobalConfig.style.font and every other figure are unaffected. Before this was fixed, this in-place edit silently mutated GlobalConfig.style itself (since fig.style and GlobalConfig.style were the same object), leaking into every figure created afterwards in the process.

classmethod reset()[source]

Reset all configurations to defaults.

classmethod get_style()[source]

Get global style configuration.

Return type:

GLEStyleConfig

classmethod get_graph()[source]

Get global graph configuration.

Return type:

GLEGraphConfig

classmethod get_marker()[source]

Get global marker configuration.

Return type:

GLEMarkerConfig

classmethod to_dict()[source]

Export all configurations as dictionary.

Return type:

Dict[str, Dict[str, Any]]

Functions

gleplot.figure(figsize=(8, 6), dpi=100, style=None, graph=None, marker=None, data_prefix=None, height_ratios=None, width_ratios=None)[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.

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='helvetica', fontsize=12)
>>> fig = glp.figure(style=style)

Or modify global defaults:

>>> glp.GlobalConfig.style.font = 'helvetica'
>>> fig = glp.figure()  # Will use helvetica font

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, figsize=None, dpi=100, style=None, graph=None, marker=None, sharex=False, sharey=False, data_prefix=None, height_ratios=None, width_ratios=None)[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

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

  • sharex (bool, optional) – If True, all subplots share the same x-axis. Only the bottom row will show x-axis labels and ticks. Default: False

  • sharey (bool, optional) – If True, all subplots share the same y-axis. Only the leftmost column will show y-axis labels and ticks. Default: False

  • 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 of the nrows subplot rows, matplotlib- gridspec style (e.g. [3, 3, 3, 1, 4] for 5 rows whose 4th is thin). Must have length nrows if given. None (default) keeps every row the same height – the historical behaviour, byte- identical output. See gleplot.figure.Figure for full semantics (validated against the actual row count at GLE-generation time).

  • width_ratios (sequence of float, optional) – Relative width of each of the ncols subplot columns. Same semantics as height_ratios, for columns; must have length ncols if given.

Returns:

  • fig (Figure) – The figure object.

  • axes (Axes or list of Axes) – A single Axes if nrows*ncols == 1, otherwise a list of Axes arranged in row-major order.

Examples

Single plot:

>>> fig, ax = glp.subplots()
>>> ax.plot(x, y)

2x2 grid:

>>> fig, axes = glp.subplots(2, 2, figsize=(12, 10))
>>> axes[0].plot(x, y1)   # top-left
>>> axes[1].scatter(x, y2)  # top-right
>>> axes[2].bar(x, y3)      # bottom-left
>>> axes[3].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.scatter(*args, **kwargs)[source]

Scatter on current axes.

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

Bar chart on current axes.

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

Fill between on current axes.

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

Draw contour lines 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(*args, **kwargs)[source]

Attach a colorbar to the current figure’s heatmap axes.

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

Add text annotation on current axes.

gleplot.xlabel(label)[source]

Set x label on current axes.

Parameters:

label (str)

gleplot.ylabel(label)[source]

Set y label on current axes.

Parameters:

label (str)

gleplot.title(label)[source]

Set title on current axes.

Parameters:

label (str)

gleplot.legend(**kwargs)[source]

Add legend to current axes.

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

Save current figure.

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 current figure (placeholder).

gleplot.close(fig=None)[source]

Close figure.

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 or tuple) – Matplotlib color: a name, a single-letter code, a C0..``C9`` cycle reference, a tab: name, a #RRGGBB/#RGB hex string, an RGB tuple/list 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

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)[source]

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

Compiler

class gleplot.GLECompiler(gle_path=None)[source]

Wrapper for GLE command-line compiler.

When gle_path is not given explicitly, the GLE executable is located via find_gle(), which searches (in order) the GLE_PATH environment variable, PATH (via shutil.which()), and a set of platform-specific well-known install locations. Set GLE_PATH to pin a specific GLE binary, e.g. when multiple versions are installed.

Parameters:

gle_path (str | None)

compile(input_file, output_format='pdf', dpi=150, verbose=False, timeout=30, cairo=False)[source]

Compile GLE file to output format.

Parameters:
  • input_file (str) – Path to .gle input file

  • output_format ({'pdf', 'png', 'eps', 'jpg', 'svg'}) – Output format

  • dpi (int) – DPI for raster formats (png, jpg)

  • verbose (bool) – Print compiler output

  • timeout (int) – Maximum number of seconds to allow the GLE process to run.

  • cairo (bool) – Whether to pass GLE’s -cairo device flag (SPEC §6.1/§10.6). Required for any script using semi-transparency (an rgba(...)/rgba255(...) colour – e.g. a fill_between with alpha < 1); without it GLE fails outright on such a script (semi-transparency only supported with command line option '-cairo'). This method has no Figure to inspect, so it never decides this for you – cairo is an explicit, caller-supplied override. gleplot.figure.Figure.savefig() is the caller that does have the figure and passes figure.requires_cairo() here automatically; pass an explicit True/False yourself when compiling a .gle file this compiler didn’t write (or to force the flag either way).

Returns:

Path to output file

Return type:

Path

Raises:
  • FileNotFoundError – If the input file does not exist.

  • GLECompileError – If compilation fails (nonzero exit code, or the expected output file was not produced). Carries structured errors and the raw_output from the GLE process.

info()[source]

Get GLE version and info.

Return type:

dict