Module functions
gleplot - write standard GLE from Python, with matplotlib-shaped names
A Python library that writes GLE (Graphics Layout Engine) scripts for publication-quality vector graphics, through matplotlib-shaped calls.
Features
Matplotlib-compatible API (plot, scatter, bar, fill_between, errorbar)
Text annotations and arrows in data coordinates or axes fractions (text, annotate)
Subplots with flexible grid layouts (subplots, add_subplot)
Native vector graphics output (PDF, PNG, EPS)
Inline display in Jupyter notebooks (view)
Support for line styles, markers, and colors
Error bars (symmetric, asymmetric, horizontal)
Logarithmic scales
Legend and axis labels
Semantic per-series data file naming (data_name) and figure-level prefixes (data_prefix)
Direct GLE script generation
Usage
import gleplot as glp
fig = glp.figure(figsize=(8, 6)) ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [1, 4, 9], ‘b-’, label=’quadratic’) ax.scatter([1, 2, 3], [1, 2, 3], color=’red’, label=’points’)
ax.set_xlabel(‘X axis’) ax.set_ylabel(‘Y axis’) ax.set_title(‘Example Plot’) ax.legend()
fig.savefig(‘output.pdf’) # Saves as PDF fig.savefig(‘output.gle’) # Saves as GLE script only fig.view() # Display inline in Jupyter notebook
Classes
- Figure
Matplotlib-like figure container
- Axes
Matplotlib-like axes for plotting
Functions
- figure(figsize=(8, 6), dpi=100)
Create a new figure
Plotting helpers
- gleplot.figure(figsize=(8, 6), dpi=100, style=None, graph=None, marker=None, data_prefix=None, height_ratios=None, width_ratios=None, **kwargs)[source]
Create a new figure.
- Parameters:
figsize (tuple, optional) – Figure size (width, height) in inches. Default: (8, 6)
dpi (int, optional) – Dots per inch. Default: 100
style (GLEStyleConfig, optional) – Style configuration. If None, uses global default.
graph (GLEGraphConfig, optional) – Graph configuration. If None, uses global default.
marker (GLEMarkerConfig, optional) – Marker configuration. If None, uses global default.
data_prefix (str, optional) – Custom prefix for data file names (e.g., ‘test9’ creates ‘test9_0.dat’, ‘test9_1.dat’). If None, uses global counter with
data_prefix. Used verbatim, so it must be usable as a GLE data filename: whitespace, control characters and any of! " + / \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.**kwargs – Any other matplotlib keyword (
num,facecolor, …) warns and is ignored.
- 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='texcmss', fontsize=12) >>> fig = glp.figure(style=style)
Or modify global defaults:
>>> glp.GlobalConfig.style.font = 'texcmss' >>> fig = glp.figure() # Will use Computer Modern Sans Serif
A 5-row grid built with add_subplot, with a short 4th “separator” row:
>>> fig = glp.figure(figsize=(3.4, 5.2), height_ratios=[3, 3, 3, 1, 4]) >>> axes = [fig.add_subplot(5, 1, i) for i in range(1, 6)]
- gleplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, figsize=None, dpi=100, style=None, graph=None, marker=None, data_prefix=None, **fig_kw)[source]
Create a figure and a set of subplots.
Convenience function matching
matplotlib.pyplot.subplots().- Parameters:
nrows (int, optional) – Number of rows of subplots. Default: 1
ncols (int, optional) – Number of columns of subplots. Default: 1
sharex (bool or {'all', 'none', 'row', 'col'}, default: False) – As in matplotlib:
Trueor'all'gives every subplot one x range,'col'one per column and'row'one per row. WithTrueand'col'only the bottom row shows x tick labels and the x-axis label.Falseor'none'shares nothing; another value raisesValueError.sharey (bool or {'all', 'none', 'row', 'col'}, default: False) – The same for the y axis:
'row'gives one y range per row and, likeTrue, shows y tick labels only in the leftmost column;'col'gives one per column.squeeze (bool, default: True) – As in matplotlib: if True, drop the extra dimensions of the returned array, so a single subplot comes back as an
Axesand a single row or column as a 1-D array. If False, always return a 2-D array, even for a 1x1 grid.width_ratios (sequence of float, optional) – Relative width of each of the
ncolssubplot columns, matplotlib-gridspecstyle (e.g.[1, 3]makes the second of two columns three times as wide). Must have lengthncolsif given.None(default) keeps every column the same width. Seegleplot.figure.Figurefor full semantics (validated against the actual column count at GLE-generation time).height_ratios (sequence of float, optional) – Relative height of each of the
nrowssubplot rows (e.g.[3, 3, 3, 1, 4]for 5 rows whose 4th is thin). Same semantics aswidth_ratios, for rows; must have lengthnrowsif given.subplot_kw (dict, optional) – As in matplotlib, keywords for each
Figure.add_subplot()call, such asprojection='polar'.gridspec_kw (dict, optional) – As in matplotlib, the grid’s layout.
width_ratiosandheight_ratiosare as the parameters (giving one both ways raisesValueError);left,right,bottom,top,wspaceandhspaceare passed toFigure.subplots_adjust(); other keys warn and are ignored.figsize (tuple, optional) – Figure size (width, height) in inches. If None, auto-scales based on grid size (6 inches per column, 4 inches per row).
dpi (int, optional) – Dots per inch. Default: 100
style (GLEStyleConfig, optional) – Style configuration.
graph (GLEGraphConfig, optional) – Graph configuration.
marker (GLEMarkerConfig, optional) – Marker configuration.
data_prefix (str, optional) – Custom prefix for data file names (e.g., ‘test9’ creates ‘test9_0.dat’, ‘test9_1.dat’). If None, uses global counter with
data_prefix. Used verbatim, so it must be usable as a GLE data filename: whitespace, control characters and any of! " + / \raiseValueError.**fig_kw – matplotlib’s other
matplotlib.pyplot.figure()keywords, such asnumorlayout. gleplot has none of them: they warn and are ignored.
- Returns:
fig (Figure) – The figure object.
axes (Axes or numpy.ndarray of Axes) – The subplots in a
(nrows, ncols)object array, indexedaxes[row, col], squeezed as described forsqueeze.
Notes
As in matplotlib, every parameter after
ncolsis keyword-only.figsizeand the other figure settings are the keywordsfigure()takes;figsizeis in inches.Examples
Single plot:
>>> fig, ax = glp.subplots() >>> ax.plot(x, y)
2x2 grid:
>>> fig, axes = glp.subplots(2, 2, figsize=(12, 10)) >>> axes[0, 0].plot(x, y1) # top-left >>> axes[0, 1].scatter(x, y2) # top-right >>> axes[1, 0].bar(x, y3) # bottom-left >>> axes[1, 1].plot(x, y4) # bottom-right
Shared x-axis (stacked plots):
>>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(8, 12)) >>> # Only bottom subplot shows x-axis label and ticks
Stacked panels with a short separator row (unequal row heights):
>>> fig, axes = glp.subplots(3, 1, sharex=True, figsize=(3.4, 4), ... height_ratios=[3, 3, 1]) >>> # axes[2] gets 1/7 of the plotting height, axes[0]/axes[1] get 3/7 each
- gleplot.step(*args, **kwargs)[source]
Step plot on current axes. See
gleplot.Axes.step().
- gleplot.stem(*args, **kwargs)[source]
Stem plot on current axes. See
gleplot.Axes.stem().
- gleplot.hist(*args, **kwargs)[source]
Histogram on the current axes. See
gleplot.Axes.hist().
- gleplot.barh(*args, **kwargs)[source]
Horizontal bars on the current axes. See
gleplot.Axes.barh().
- gleplot.fill_between(*args, **kwargs)[source]
Fill between on current axes. See
gleplot.Axes.fill_between().
- gleplot.stackplot(*args, **kwargs)[source]
Stacked bands on the current axes. See
gleplot.Axes.stackplot().
- gleplot.fill(*args, **kwargs)[source]
Fill a polygon on the current axes. See
gleplot.Axes.fill().
- gleplot.pcolormesh(*args, **kwargs)[source]
Colour the cells of a rectangular grid on current axes.
- gleplot.colorbar(mappable=None, cax=None, ax=None, **kwargs)[source]
Attach a colorbar to a heatmap or colour-mapped scatter on the current figure.
See
Figure.colorbar().
- gleplot.annotate(*args, **kwargs)[source]
Annotate a point on current axes, optionally with an arrow.
- gleplot.hlines(*args, **kwargs)[source]
Horizontal segments on the current axes. See
gleplot.Axes.hlines().
- gleplot.vlines(*args, **kwargs)[source]
Vertical segments on the current axes. See
gleplot.Axes.vlines().
- gleplot.axis(arg=None, /, *, emit=True, **kwargs)[source]
Get or set the limits of, or hide, the current axes. See
Axes.axis().
- gleplot.xlabel(label, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]
Set x label on current axes:
Axes.set_xlabel()ongca().- Parameters:
label (str)
- gleplot.ylabel(label, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]
Set y label on current axes:
Axes.set_ylabel()ongca().- Parameters:
label (str)
- gleplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)[source]
Set title on current axes:
Axes.set_title()ongca().ywarns and is ignored, as onAxes.set_title().- Parameters:
label (str)
- gleplot.savefig(filepath, **kwargs)[source]
Save current figure:
Figure.savefig()ongcf().A keyword
Figure.savefigdoes not take warns and is ignored.- Parameters:
filepath (str)
- gleplot.view(dpi=None, format='png')[source]
Display current figure inline (in Jupyter notebooks).
- Parameters:
dpi (int, optional) – Resolution in dots per inch. If None, uses figure’s dpi setting.
format ({'png', 'pdf'}, optional) – Output format. Default is ‘png’ for inline display.
- Returns:
Path to the generated file, or None when displayed inline in Jupyter.
- Return type:
Path or None
Examples
>>> import gleplot as glp >>> fig = glp.figure() >>> ax = fig.add_subplot(111) >>> ax.plot([1, 2, 3], [1, 4, 9]) >>> glp.view() # Display in notebook
- gleplot.show()[source]
Show the current figure, as
view()does with its defaults.In a Jupyter notebook the figure is displayed inline. Elsewhere it is rendered to a temporary PNG and nothing is printed: open the returned path.
- Returns:
Path to the temporary file, or None when displayed inline in Jupyter.
- Return type:
Path or None
- Raises:
RuntimeError – If GLE is not installed.
Utilities
- gleplot.rgb_to_gle(color)[source]
Convert a matplotlib color specification to a GLE color token.
A recognised GLE colour name is returned as that name (uppercased); everything else is returned as an exact
rgb255(r,g,b)expression, so no requested colour is ever silently replaced by a different one.- Parameters:
color (str, tuple, list or numpy.ndarray) – Matplotlib color: a name, a single-letter code, a
C0..``C9`` cycle reference, atab:name, a#RRGGBB/#RGBhex string, a grey level as a number string in [0, 1] ('0.3'), an RGB tuple/list/1-D array with components in [0, 1], or an already-formed GLE colour expression.- Returns:
A GLE colour token: an uppercase GLE colour name, or
rgb255(r,g,b).- Return type:
- Raises:
ValueError – For a string that is none of the forms above, a grey level outside [0, 1], or a sequence of fewer than 3 numbers.
TypeError – For a value that is neither a string nor a sequence of numbers.
Examples
>>> rgb_to_gle('blue') 'BLUE' >>> rgb_to_gle('b') 'BLUE' >>> rgb_to_gle((0.0, 0.0, 1.0)) 'rgb255(0,0,255)' >>> rgb_to_gle('#8c8c8c') 'rgb255(140,140,140)' >>> rgb_to_gle('rgb255(140, 140, 140)') 'rgb255(140,140,140)'
- gleplot.get_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: str) str[source]
- gleplot.mathtext_to_gle(s: None) None
Translate matplotlib mathtext (
$...$) in s into GLE text markup.- Parameters:
s (str or None) – A display string as a matplotlib user would write it. Non-strings (including
None) are returned unchanged, so callers may pass an optional label straight through.- Returns:
The string with every
$...$math segment rewritten in GLE markup and every non-math segment escaped so it renders literally (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
- gleplot.validate_tick_format(fmt)[source]
Light validation of a GLE number-format string; returns it stripped.
Used by
Axes.set_tick_format()and available to callers building a format string interactively (GLEstudio’s format preset builder). The check is deliberately weak, because GLE’s own parser is:gleplot.parser.tables.NUMBER_FORMAT_KEYWORDSdocuments that an unrecognized specifier is skipped with a printed note, not an error. So this only rules out the strings that could not possibly be a format – empty, multi-line, or not starting with a keyword GLE knows – and lets everything else (including arguments this version has never seen) through unchanged.- Parameters:
fmt (str) – Candidate format string, e.g.
"fix 1"or"sci 2 10 expsign".- Returns:
fmtwith surrounding whitespace removed.- Return type:
- Raises:
ValueError – If
fmtis not a string, is blank, spans multiple lines, or does not begin with a GLE number-format keyword.