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
styleis taken at construction time – see the “Global defaults are copied, not shared” note below. An explicitly passedstyleis stored by reference, as before.graph (GLEGraphConfig, optional) – Graph configuration. If None, a COPY of
graphis taken at construction time (same note). An explicitly passedgraphis stored by reference, as before.marker (GLEMarkerConfig, optional) – Marker configuration. If None, a COPY of
markeris taken at construction time (same note). An explicitly passedmarkeris stored by reference, as before.sharex (bool)
sharey (bool)
data_prefix (str | None)
Notes
Global defaults are copied, not shared.
GlobalConfig.style/.graph/.markerare process-wide singletons. SettingGlobalConfig.style.font = 'helvetica'before creating a figure still changes that figure’s default font, exactly as documented ingleplot.config.GlobalConfig. But once aFigureexists, itsstyle/graph/marker_configare independent objects (when no explicit config was passed in): editingfig.style.fontin place (or reassigningfig.style) affects onlyfig– it can neither leak into other figures created earlier or later in the same process, nor mutateGlobalConfigitself. This is copy-AT-CONSTRUCTION semantics, the same rule matplotlib’srcParamssnapshot follows for a newFigure/Axes.This only applies to the default, taken from
GlobalConfig. Astyle/graph/markerobject 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.recognizerdoes exactly this while reconstructing aFigurefrom 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_glerather 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 passedpreview_decimation=N(N> 1) AND at least one eligible series (line/scatter – seegleplot.writer.GLEWriter._deresolve_clause()for the full kind/ threshold rule) metgleplot.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 latestsavefig/savefig_glerather 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).
- 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:
- 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 (%)')
- 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:
- 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/vmaxto 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
GridRefhas 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 computeszmin/zmax/zstepfrom the data that write resolved, so a table edit re-flows into the bar instead of leaving a range baked atcolorbar()time. Explicitvmin/vmaxon the heatmap short-circuit that and are used as-is, here and at write time alike.
- absolutize_file_references(base_dir)[source]
Rewrite relative reference-mode data paths to absolute paths.
Reference-mode series (
file_series) carry theirdata_fileverbatim into the generateddatacommand, 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_sourcereferences a table (seesavefig()andgleplot.sources).preview_decimation (DecimationPolicy, optional) – Preview-only
deresolvefactor (SPEC §6.1/§10.7).None(the default) emits byte-identically to a build before this option existed. A singleintapplies one factor to every eligible series (unchanged, byte-for-byte, since G7); aMappingkeyed by series label or a per-seriesCallable[[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 – seegleplot.writer.DecimationPolicyfor the full contract. When a resolved factor is given and > 1, large line/scatter series (seegleplot.writer.GLEWriter.MIN_DERESOLVE_POINTS) get a `` deresolve N`` clause on theirdNline – 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, soto_dict/from_dictand a saved.gleare unaffected – pass it only when writing a throwaway preview copy, never the document being saved. Seepreview_decimation_reportfor what got decimated.folder (bool, optional) – If True, place the
.glescript and generated data files in a sibling<name>.gleplotdirectory.**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 (
.jpegmaps tojpg); an unrecognized or missing suffix defaults to saving the.glescript 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
-cairodevice flag (SPEC §6.1/§10.6).None(the default) auto-detects viarequires_cairo()– on for any figure using semi- transparency, off otherwise, so an ordinary opaque figure’s compile behaviour (and its written.gletext – the flag is compile-time only, never script-time) is completely unchanged. PassTrue/Falseto force the flag either way. Ignored whenformatis'gle'(no compile happens).When Cairo ends up active (auto or forced) and this figure’s configured font (
style’sfont) is not one of GLE’s Cairo-safe fonts, aUserWarningis raised: GLE itself substitutes a Cairo-safe font in that case (seegleplot.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/GridRefseries reference (gleplot.sources). Injected here, at write time, rather than held on the figure: the figure is a serializable document thatto_dictround-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/
fitzintermediates (-cdata.dat/-clabels.dat/-cvalues.dat, and a points-sourced heatmap/contour’s generated.z) that a compiled export otherwise removes fromexport_dirafterwards – see the “Engine intermediates” note below. Default False. Has no effect when this figure has no contour/heatmap series, or whenformat == 'gle'(no compile runs, so nothing was generated to clean up).preview_decimation (DecimationPolicy, optional) – Preview-only
deresolvefactor – seesavefig_gle()for the full contract. Generation-time only, never stored on the figure. Compiling with this set still produces a realformatoutput (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
.glescript, and generated data files in a sibling<name>.gleplotdirectory.**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 theglebinary itself write extra files intoexport_diras 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 fromexport_dirafterwards 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 (seegleplot.compiler.remove_generated_intermediates()). Passkeep_intermediates=Trueto 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
figureblock 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 ownto_dict), and every axes with all of its series and state (including its ownpassthroughbucket) viaAxes.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
Noneand are re-derived from data at GLE-generation time – keeping the format independent of that (order-dependent, potentially expensive) derivation. Callingto_dicttwice on an unchanged figure yields an identical dict.The generated-series
data_filenames 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 afterfrom_dict()in a fresh process picks up where the original session left off instead of restarting at 0 and colliding with (or duplicating) previously useddata_N.datnames. The contour/heatmap/fitz sidecar counters get the same treatment (sidecar_countersfor a figure with a customdata_prefix,global_sidecar_countersfor the shared default-prefix counter – seeaxes._reserve_sidecar), so a figure reloaded viafrom_dict()and then given a new contour/heatmap series keeps numbering forward rather than restarting at1.- Returns:
JSON-serializable project dictionary.
- Return type:
- requires_cairo()[source]
Whether rendering this figure needs GLE’s
-cairodevice flag.True whenever the figure uses semi-transparency anywhere it can appear – a
fill_between/axvspan/axhspanwithalpha < 1(Axes.fill_between(),Axes.axvspan(),Axes.axhspan()), or any colour expressed directly asrgba(...)/rgba255(...). Seegleplot.cairo_support.figure_requires_cairo()for the exact rule andgleplot.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 theiralphafrom 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:
- classmethod from_dict(d)[source]
Reconstruct an equivalent
Figurefrom a project dict.- Parameters:
- Returns:
A figure equivalent to the one that was serialized: round-tripping through
to_dict()reproduces an equal dictionary and regenerated GLE (with the samedata_prefix) is byte-identical.- Return type:
- Raises:
ValueError – If the envelope
formatis missing/unrecognized or theversionis unsupported.
Notes
Unknown keys inside the envelope, the
figureblock, and theconfigsub-dicts (style/graph/marker) are ignored for forward compatibility.The module-global data-file counter (used to name auto-generated
data_N.datseries when a figure has no customdata_prefix) is restored tomax(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.
Axes
- class gleplot.Axes(figure, position=None)[source]
Matplotlib-like axes for plotting.
- 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_dictround-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’slegend_offset_x/legend_offset_y, themselves0, 0by default, i.e. nooffsetclause at all).
- xformat: str | None
Tick-label number format per axis – GLE
xaxis format "<fmt>"(seeset_tick_format()for the syntax and validation).
- xgrid_lstyle: int | None
Grid line style, width (points) and colour. Emitted as
xticks lstyle/lwidth/colorand, when the grid covers subticks, the matchingxsubticksclause – 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/y2titletext isxlabel_text/… above; these are itshei/color/distoptions.*_distis the gap between the title and the tick labels (None = the figure graph config’sxlabel_distance/ylabel_distance, themselves None = GLE’satitledist).
- xticklabel_size: float | None
xlabels hei/colorplusxaxis 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 onis given, so setting any y2 tick-label property (includingy2format) also turns them on – otherwise the property would be inert. SeeGLEWriter.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_distNone = the figure graph config’stitle_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 tofillstyle='none';'white'gives an outline marker with an opaque white interior. Also accepted as the matplotlib aliasmfc.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 tofillstyle='none';'white'gives an outline marker with an opaque white interior. Also accepted as the matplotlib aliasmfc.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_*.datfiles. Column indices are 1-based to match GLE conventions.fillstyle='none'/markerfacecolor='none'(aliasmfc) select an open marker;markerfacecolor='white'selects a white-filled one.
- 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_*.datfiles for overlay lines. Column indices are 1-based to match GLE conventions.
- SCATTER_DEFAULT_S = 20
Default
scattersize, 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’sscattersize, 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’smsizethe same wayplot()does it.markersize– a diameter in points, matplotlib’sLine2Dconvention and exactly whatplot()takes. Used as given, with no area conversion, so ascatterand aplotasking for the samemarkersizedraw 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
scatterconvention). Default 20 when neithersnormarkersizeis given. A per-point array is not supported: GLE’smsizeis 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 overs.fillstyle ({'full', 'none'}, optional) –
'none'draws open (outline) markers instead of filled ones.markerfacecolor (str, optional) –
'none'is equivalent tofillstyle='none';'white'gives outline markers with an opaque white interior. Also accepted as the matplotlib aliasmfc.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 constant0.8default – every bar chart written before this parameter existed must keep emitting the script it emits now. Note also thatwidthis a keyword here where matplotlib’s is positional: this method’s third positional parameter has always beencolor.**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_betweenand keeping every pre-Cairo-support figure’s.gleoutput byte-identical unless a caller actually asks for transparency. Below 1.0, the fill is genuinely semi-transparent (gleplot.colors.apply_alphacomposes anrgba255(...)colour) and rendering it requires GLE’s Cairo device, which gleplot’s compile pipeline enables automatically – seegleplot.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):
0is the bottom of the axes,1the top.ymax (float) – Vertical extent as a fraction of the axes height (matplotlib semantics):
0is the bottom of the axes,1the 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:
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/xmaxare the horizontal extent as a fraction of the axes width (matplotlib semantics). Seeaxvline()for the rest.
- 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
xminandxmax.- 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
.gleoutput byte-identical unless a caller actually asks for transparency. Below 1.0, the band is genuinely semi-transparent (gleplot.colors.apply_alphacomposes anrgba255(...)colour, exactly asfill_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 – seegleplot.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:
- 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
yminandymax.xmin/xmaxare the horizontal extent as a fraction of the axes width (matplotlib semantics). Seeaxvspan()for the rest, including thealphabehaviour.
- static guide_spanned_bounds(entry, limits)[source]
The
(lo, hi)bounds of the axisentryspans, fromlimits.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
Noneat 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 layereddrawoverxgmin/ygmaxinstead (gleplot.guides).False – the overwhelmingly common case – keeps the historical two-point dataset emission untouched, byte for byte.
- Return type:
- engine_range_guides(series_list, limits)[source]
The visible guides in
series_listrouted to the draw form.- Return type:
List[Series]
- dataset_form_guides(series_list, limits)[source]
The visible guides in
series_listthat 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 whatmaterialize_reflines()/materialize_spans()return for the samelimits. 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_contentchecks the two lists are the same length rather than trusting it silently.- Return type:
List[Series]
- materialize_reflines(limits)[source]
Turn
self.reflinesinto 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 forGLEWriter.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 whosespanned axis has an unresolved bound. The latter are the figures the
literal dataset got wrong; they are emitted as
drawcalls instead(see
guide_needs_engine_range()andgleplot.guides), andengine_range_guides()is how the writer collects them.
- Return type:
List[LineSeries]
- materialize_spans(limits)[source]
Turn
self.spansinto 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
Zas 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 ofZatymin(the scientific convention; note this differs from matplotlib’s'upper'default).'upper'flips the rows when writing the.zsidecar.cmap (str, optional) – Palette name (see
gleplot.palettes.SUPPORTED_CMAPS). WhenNone, uses the figure graph config’sdefault_cmap.vmin (float, optional) – Colour normalization range (GLE
zmin/zmax).Noneuses GLE’s data-range default.vmax (float, optional) – Colour normalization range (GLE
zmin/zmax).Noneuses GLE’s data-range default.interpolation ({'bicubic', 'nearest'}) – Sampling interpolation for the
.zgrid.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:
- 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)orcontour(x, y, Z)with 1-Dx(nx), 1-Dy(ny), 2-DZ(ny, nx).x/ymust be uniformly spaced.The matplotlib spelling
contour(X, Y, Z)with 2-DX/Yfromnp.meshgridis also accepted: the grid is checked for regularity (constant rows inX, constant columns inY) and its 1-D axes extracted, since GLE’s.zgrid is an extent plus a shape. A genuinely irregular grid raises – usetricontour()for scattered data.- Parameters:
levels (None, int, or sequence) –
Noneuses GLE’s default 10 levels. An intnemitsvalues from zmin to zmax step (zmax-zmin)/n. A sequence emitsvalues 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:
- 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 GLEfitzgridding.Writes a points sidecar (raw
x y ztriples) and emits abegin fitzblock that grids the data (Akima interpolation) to a.zfile at GLE compile time, then acolormapof 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 GLEfitz.Writes a points sidecar and emits a
begin fitzblock (gridding at compile time) followed by abegin contourblock on the generated.zgrid.- Parameters:
:param (remaining kwargs as
contour()).:
- set_xlim(xmin, xmax)[source]
Set x-axis limits.
Noneputs 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.
- set_ylim(ymin, ymax, axis='y')[source]
Set y-axis limits.
- Parameters:
ymin (float or None) – Axis limits;
None= auto (seeset_xlim()).ymax (float or None) – Axis limits;
None= auto (seeset_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). PassingNoneleaves 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 ofticks.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().
- 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).Falseemits GLE’skey ... nobox.ncol (int, optional) – Only a single column is expressible: GLE builds multi-column keys from
separatorcommands in a standalonebegin keyblock, which gleplot does not emit.1is accepted; anything else warns.ncols (int, optional) – Only a single column is expressible: GLE builds multi-column keys from
separatorcommands in a standalonebegin keyblock, which gleplot does not emit.1is accepted; anything else warns.**kwargs – Any other matplotlib legend keyword has no GLE
keyequivalent 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 gridmakes 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'addsxsubticks 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 GLElstylenumber.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:
- Raises:
ValueError – On an unknown
which/axis/linestylevalue, a non-positivelinewidth, 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>").fmtis a GLE format string – the same syntax as theformat$()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:
- 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 onis given, so settingaxis='y2'also turns them on at write time – seegleplot.writer.GLEWriter.add_axes().
- get_xlim()[source]
Get x-axis limits.
Either bound is
Nonewhen it is on AUTO – to be derived from the data at GLE-generation time – which is how every figure starts out.
- get_ylim(axis='y')[source]
Get y-axis limits (
None= auto, seeget_xlim()).
- 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_filename 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:
- classmethod from_dict(figure, d)[source]
Reconstruct an
Axesfrom ato_dict()payload.- Parameters:
- Return type:
:param Each series is rebuilt as its
gleplot.seriesclass: :param whose: :paramARRAY_FIELDSsay which values are restored tofloatnumpy: :param arrays; optional error arrays that wereNonestayNone. All: :param style keys: :param labels and thedata_filenames 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
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:
- default_linewidth
Default line width in points (unit: 1/72 inch). Default: 1.5 points ≈ 0.053 cm (increased for visibility in PDFs)
- Type:
- default_color
Colour used by
gleplot.Axes.plot(),errorbar(),errorbar_from_file()andline_from_file()when the call passes nocolor. Any spellinggleplot.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()andfill_between()keep their own distinct defaults, RED and LIGHTBLUE.)- Type:
- default_marker_color
Same, for a marker-only series – what
gleplot.Axes.scatter()produces, andplot()with a marker and no line. Default: ‘BLUE’- Type:
- line_style_solid
GLE line style for solid lines. Default: 1
- Type:
- line_style_dashed
GLE line style for dashed lines (–). Default: 3
- Type:
- line_style_dotted
GLE line style for dotted lines (:). Default: 2
- Type:
- line_style_dashdot
GLE line style for dash-dot lines (-.). Default: 6
- Type:
Notes
The
line_style_*defaults are the GLElstylenumbers that actually render as their names say, measured by compiling a ruler ofset lstyle 1..9strokes with GLE 4.3.10 and looking at the result:lstylerenders 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
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
Graph scaling mode: ‘auto’ (auto-sizes and centers), ‘fixed’ (uses specified size), or ‘fullsize’ (axes fill entire box, no margins). Default: ‘auto’
- Type:
- title_distance
Figure-wide default for
Axes.title_dist– thedistoption of GLE’stitlecommand, in cm. A per-axestitle_distwins over it.None(the default) emits nodistat all, leaving GLE’s own spacing.Changed in version 2.4: Was an inert
0.1that nothing read. It is now the default for the per-axes distance, and its default isNoneso that figures which never set it emit exactly the GLE they always did. A project serialized with the old inert0.1will, once reloaded, actually emitdist 0.1.- Type:
float or None
- xlabel_distance
Same, for
Axes.xlabel_dist– thedistoption of GLE’sxtitlecommand (distance between the axis title and the tick labels), in cm. Default: None.- Type:
float or None
- ylabel_distance
Same, for
Axes.ylabel_dist(GLEytitle ... 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:
- legend_offset_x
Figure-wide default legend x-offset from its anchor (cm), used by every axes whose own
legend_offsetis None. Default: 0.0.- Type:
- legend_offset_y
The y half of the same default (cm). Default: 0.0.
(0.0, 0.0)means “no offset”, and emits nooffsetclause – so the defaults leave GLE output unchanged.- Type:
- smooth_curves
Draw line series as a fitted spline through the points (GLE’s
smoothkeyword) 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:
- 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 (GLExaxis grid/yaxis grid). An axes that HAS calledgrid()– includinggrid(False)– keeps its own answer. Default: False- Type:
- default_cmap
Default colour map used by
imshow/tripcolorwhencmapis not passed. One of the names ingleplot.palettes.SUPPORTED_CMAPS. Default: ‘viridis’- Type:
- colormap_pixels
Default bitmap resolution (pixels per side) for
colormaprendering whenimshow(pixels=...)is not given. Default: 200- Type:
- scale_mode: str = 'auto'
- 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
GLEMarkerConfig
- class gleplot.GLEMarkerConfig(default_marker='fcircle', msize_scale=1.0, mdist=None)[source]
Marker style configuration.
- 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:
- msize_scale
Scaling factor for marker sizes. Multiplies the msize value. Default: 1.0
- Type:
- 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
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. Butgleplot.figure.Figureandgleplot.writer.GLEWritereach take an independent COPY of the current value at construction time (when their ownstyle/graph/markerargument is omitted), not a reference to this singleton. So:GlobalConfig.style.font = 'x'thenfig = Figure()–figgets'x'(the default was read at construction time).fig = Figure()thenfig.style.font = 'x'– onlyfigchanges;GlobalConfig.style.fontand every other figure are unaffected. Before this was fixed, this in-place edit silently mutatedGlobalConfig.styleitself (sincefig.styleandGlobalConfig.stylewere the same object), leaking into every figure created afterwards in the process.
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! " + / \raiseValueError.height_ratios (sequence of float, optional) – Relative height of each subplot ROW for the grid built with subsequent
Figure.add_subplot()calls, matplotlib-gridspecstyle.None(default) keeps every row the same height. Seegleplot.figure.Figurefor full semantics (validated against the actual row count at GLE-generation time, once everyadd_subplothas 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:
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.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! " + / \raiseValueError.height_ratios (sequence of float, optional) – Relative height of each of the
nrowssubplot rows, matplotlib-gridspecstyle (e.g.[3, 3, 3, 1, 4]for 5 rows whose 4th is thin). Must have lengthnrowsif given.None(default) keeps every row the same height – the historical behaviour, byte- identical output. Seegleplot.figure.Figurefor full semantics (validated against the actual row count at GLE-generation time).width_ratios (sequence of float, optional) – Relative width of each of the
ncolssubplot columns. Same semantics asheight_ratios, for columns; must have lengthncolsif 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.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
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, atab:name, a#RRGGBB/#RGBhex 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:
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_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
Nonewhen no marker was requested.- Return type:
str or None
- Raises:
ValueError – If
fillis not one ofMARKER_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 (seeescape_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_pathis not given explicitly, the GLE executable is located viafind_gle(), which searches (in order) theGLE_PATHenvironment variable,PATH(viashutil.which()), and a set of platform-specific well-known install locations. SetGLE_PATHto 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
-cairodevice flag (SPEC §6.1/§10.6). Required for any script using semi-transparency (anrgba(...)/rgba255(...)colour – e.g. afill_betweenwithalpha < 1); without it GLE fails outright on such a script (semi-transparency only supported with command line option '-cairo'). This method has noFigureto inspect, so it never decides this for you –cairois an explicit, caller-supplied override.gleplot.figure.Figure.savefig()is the caller that does have the figure and passesfigure.requires_cairo()here automatically; pass an explicitTrue/Falseyourself when compiling a.glefile 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
errorsand theraw_outputfrom the GLE process.