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.data_prefix (str | None)
Notes
Global defaults are copied, not shared.
GlobalConfig.style/.graph/.markerare process-wide singletons. SettingGlobalConfig.style.font = 'texcmss'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).- texts: List[TextAnnotation]
The figure texts (
text()), in call order. Theirxandyare figure fractions.
- 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 axes: List[Axes]
The figure’s axes, in the order they were added.
A new list on each access, as in matplotlib: add axes with
add_subplot()oradd_axes(), not by changing the list. For a figure fromgleplot.open_gle(), the order is that of the graph blocks in the file.Notes
Unlike matplotlib, the secondary axes that
gleplot.Axes.twinx()andgleplot.Axes.twiny()return are not entries: they draw on their parent axes’ graph.
- 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.
- 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_subplot(*args, projection=None, polar=False, **kwargs)[source]
Add subplot to figure.
- Parameters:
*args (int or (int, int)) – Subplot specification (rows, cols, index) or single int E.g., add_subplot(2, 2, 1) or add_subplot(221). Omitted, the figure’s only subplot,
(1, 1, 1). An index that is a(first, last)tuple spans every cell of the rectangle between those two, as in matplotlib:add_subplot(2, 2, (1, 2))takes the whole top row. Any other index, or one outside1..rows*cols, raisesValueError, as in matplotlib.projection ({None, 'rectilinear', 'polar'}, optional) –
'polar'makes a polar axes:Axes.plot()andAxes.scatter()take(theta, r)with theta in radians, andAxes.function()readsxin its expression as theta.set_ylim(0, rmax)sets the radial limit.polar (bool, default: False) –
Trueisprojection='polar'.**kwargs – Axes properties, as for
add_axes():facecolor(aliasfc) is honoured, and the others warn and are ignored.
- Returns:
New axes object
- Return type:
Notes
A polar axes draws a grid of rings and spokes with the angles and radii labelled, in place of the frame and ticks. It supports the three methods above, the legend, the title and the radial limit; other plotting methods and cartesian settings such as
Axes.set_xlim()raiseNotImplementedError.
- add_axes(rect, projection=None, polar=False, **kwargs)[source]
Add an axes at a given place on the page, such as an inset.
- Parameters:
rect (sequence of 4 floats) –
[left, bottom, width, height]of the axes frame, in fractions of the figure:[0, 0, 1, 1]is the whole page.projection ({None, 'rectilinear', 'polar'}, optional) – As for
add_subplot().polar (bool, default: False) –
Trueisprojection='polar'.**kwargs – Axes properties in matplotlib.
facecolor(aliasfc) is passed toAxes.set_facecolor(); the others are not supported: they warn and are ignored, so call the setters on the returned axes instead.
- Returns:
The new axes, also the figure’s current axes.
- Return type:
Notes
The axes stands outside the subplot grid: it does not move the grid, and
sharex/shareydo not apply to it. It is written after the axes added before it, so it is drawn on top of them, but unlike matplotlib it has no background unless given afacecolor, so what is behind it shows through.The rect is turned into centimetres from the figure’s
figsizewhen this is called, and is kept asAxes.placement.Examples
>>> import gleplot as glp >>> fig, ax = glp.subplots() >>> inset = fig.add_axes([0.55, 0.55, 0.3, 0.3])
True,False, ‘row’ or ‘col’; set it as forsubplots().
True,False, ‘row’ or ‘col’; set it as forsubplots().
- plot(x, y, *args, **kwargs)[source]
Plot on current axes. See
Axes.plot().
- scatter(x, y, *args, **kwargs)[source]
Scatter on current axes. See
Axes.scatter().
- barh(y, width, height=None, left=None, **kwargs)[source]
Horizontal bars on the current axes. See
Axes.barh().
- fill_between(x, y1, y2=0, **kwargs)[source]
Fill between on current axes. See
Axes.fill_between().
- fill_betweenx(y, x1, x2=0, **kwargs)[source]
Fill between two x curves on the current axes.
See
Axes.fill_betweenx().
- stackplot(x, *args, **kwargs)[source]
Stacked bands on the current axes. See
Axes.stackplot().
- fill(x, y, *args, **kwargs)[source]
Fill a polygon on the current axes. See
Axes.fill().
- errorbar(x, y, *args, **kwargs)[source]
Error bar plot on current axes. See
Axes.errorbar().
- text(x, y, s, fontdict=None, **kwargs)[source]
Add text to the figure, in figure fractions.
- Parameters:
x (float) – Position as fractions of the page:
(0, 0)is the bottom-left corner and(1, 1)the top-right, as matplotlib’s figure coordinates.y (float) – Position as fractions of the page:
(0, 0)is the bottom-left corner and(1, 1)the top-right, as matplotlib’s figure coordinates.s (str) – The text.
fontdict (dict, optional) – Text keywords, overridden by the same keyword passed directly.
**kwargs –
color,fontsize,ha,va,rotationandbbox, as forAxes.text(). Any other keyword, includingtransform, warns and is ignored.
- Returns:
The stored text, also appended to
texts.- Return type:
TextAnnotation
Notes
Written after every axes, so it sits on top of them. Use
Axes.text()to place text in one axes’ data coordinates.Examples
>>> import gleplot as glp >>> fig, axes = glp.subplots(1, 2) >>> label = fig.text(0.02, 0.98, "(a)", ha="left", va="top")
- suptitle(t, **kwargs)[source]
Add a centred title to the figure, above every axes.
- Parameters:
t (str) – The title.
x (float, default: 0.5, 0.98) – Position in figure fractions, as for
text().y (float, default: 0.5, 0.98) – Position in figure fractions, as for
text().ha ({'center', 'left', 'right'}, default: 'center') – Horizontal alignment.
va ({'top', 'center', 'bottom'}, default: 'top') – Vertical alignment.
fontsize (float or str, default: 'large') – Points, or a matplotlib size name relative to the figure’s
GLEStyleConfig.fontsize.**kwargs –
color,rotationandbbox, as fortext(). Any other keyword warns and is ignored.
- Returns:
The stored title.
- Return type:
TextAnnotation
Notes
A second call replaces the title, as in matplotlib. Unlike matplotlib, the layout lowers the top of the axes to leave room for the title, unless
subplots_adjust(top=...)sets that edge.Examples
>>> import gleplot as glp >>> fig, axes = glp.subplots(1, 2) >>> title = fig.suptitle("Sample A")
- hlines(y, xmin, xmax, *args, **kwargs)[source]
Horizontal segments on the current axes. See
Axes.hlines().
- vlines(x, ymin, ymax, *args, **kwargs)[source]
Vertical segments on the current axes. See
Axes.vlines().
- colorbar(mappable=None, cax=None, ax=None, use_gridspec=True, *, orientation=None, label=None, format=None, nticks=None, width=0.5, sep=None, **kwargs)[source]
Attach a colorbar to a heatmap or a colour-mapped scatter.
- Parameters:
mappable (HeatmapSeries, optional) – The heatmap the bar shows, as returned by
Axes.imshow(),Axes.pcolormesh(),Axes.tripcolor()orAxes.contourf(). Default: the heatmap onax, or, on an axes with no heatmap, its colour-mapped scatter (scatter(c=...)) drawn last. With noaxeither: the one axes with a heatmap, or, if no axes has one, the one axes with a colour-mapped scatter.Axes.scatter()returns the axes, not a mappable, so a scatter’s bar is chosen byax.cax (Axes, optional) – Not supported: GLE draws the bar beside the axes it belongs to, not into another one. Passing it warns and is otherwise ignored.
ax (Axes, optional) – The axes the bar is drawn beside. It must be the axes holding
mappable; with nomappable, its heatmap is the one shown.use_gridspec (bool) – Accepted for matplotlib compatibility. The subplot grid always makes room for the bar, whatever its value.
orientation ({'vertical', 'horizontal'}, optional) –
'vertical'(the default,None) draws the bar to the right of the axes;'horizontal'draws it below the axes, under the x tick labels and title.label (str, optional) – Colorbar axis label: rotated, to the right of a vertical bar’s tick numbers; centred under a horizontal one’s.
format (str, optional) – GLE
format$string for the tick labels (e.g.'fix 1'). Default: fixed-point with as many decimals as the tick values need, from the first value and the tick step.nticks (int, optional) – Approximate number of tick intervals. Default: 5, or for a
contourfwith evenly spaced levels, a tick at everyceil(len(levels) / 10)-th level (nticksreplacing the 10).width (float) – Bar thickness in cm: its width when vertical, its height when horizontal.
sep (float, optional) – Gap (cm) between the axes frame and the bar. For a vertical bar it is measured from the frame’s right edge (default 0.3). For a horizontal bar it is measured from the frame’s bottom edge to the bar’s top (default: clear of the x tick labels and title at the figure’s font size when
colorbar()is called).
- Returns:
The stored colorbar dict (also attached to the heatmap or scatter under
'colorbar').- Return type:
- Raises:
ValueError – If there is nothing to show (no heatmap or colour-mapped scatter on the figure or on
ax, or more than one axes has one and neithermappablenoraxpicks it), ifmappableis not on this figure or not onax, iforientationis not an accepted value, ifnticksis not a positive integer, or if the heatmap has neither z data nor explicitvmin/vmaxto derive a colour range from and no reference to resolve one from later.TypeError – If
mappableis not a heatmap oraxis not anAxes.
Notes
A heatmap carries at most one bar, and each axes at most one heatmap, so a grid of heatmaps shows one bar per axes, each on its own scale. A
contourf’s bar shows its bands, from its first level to its last; with unevenly spaced levels it is ticked in equal steps, and it draws noextendend caps (both warn). A scatter’s bar runs from itsvminto itsvmax; a scatter’s bar gives way to the next bar called on its axes, so an axes shows one bar. The subplot grid makes room for every bar: a vertical bar widens the gap to the right of its column (or the right margin), and a horizontal one the gap below its row (or the bottom margin).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.Any other keyword (
shrink,pad,extend, …) warns and is ignored.
- xlabel(label, **kwargs)[source]
Set x label on current axes.
Keywords are as for
Axes.set_xlabel().- Parameters:
label (str)
- ylabel(label, axis='y', **kwargs)[source]
Set y label on current axes.
- Parameters:
label (str) – Axis label text
axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right), as for
Axes.set_ylabel().**kwargs – As for
Axes.set_ylabel().
- title(label, **kwargs)[source]
Set title on current axes.
Keywords are as for
Axes.set_title().- Parameters:
label (str)
- legend(*args, **kwargs)[source]
Add one legend for the whole figure, listing every axes’ series.
- Parameters:
loc (str, default: 'upper right') – The corner of the page the legend sits in, as a matplotlib location (
'upper center','lower left', …). As in matplotlib,'best'is not supported for a figure legend and raisesValueError.bbox_to_anchor (tuple of float, optional) –
(x, y)or(x, y, width, height)in figure fractions: theloccorner of the legend sits on that point, or on that corner of the box.ncol (optional) – As for
Axes.legend().ncols (optional) – As for
Axes.legend().fontsize (optional) – As for
Axes.legend().frameon (optional) – As for
Axes.legend().facecolor (optional) – As for
Axes.legend().labelcolor (optional) – As for
Axes.legend().borderpad (float, optional) – As for
Axes.legend().handlelength (float, optional) – As for
Axes.legend().handletextpad (float, optional) – As for
Axes.legend().columnspacing (float, optional) – As for
Axes.legend().**kwargs – Any other matplotlib legend keyword warns and is ignored.
- Return type:
self
Notes
The entries are the labelled series of every axes, axes by axes in the order they were created, and each axes’ series in the order they were added. Explicit handles and labels are not supported: legend text comes from each series’
label=. While a figure legend exists, an axes draws its own legend only ifAxes.legend()was called on it, as in matplotlib. The legend is a GLEbegin keyblock written after every axes, half a font size in from the page edges its corner is anchored to. A second call replaces the legend. The layout does not make room for it: leave room withsubplots_adjust.Examples
>>> import gleplot as glp >>> fig, axes = glp.subplots(1, 2) >>> _ = axes[0].plot([0, 1], [0, 1], label="a") >>> _ = axes[1].plot([0, 1], [1, 0], label="b") >>> _ = fig.legend(loc="upper center", ncol=2)
- circle(x, y, radius, *, fill=None, color=None, linewidth=None)[source]
Draw a circle on the page, outside any axes.
- Parameters:
x (float) – Centre, in cm from the bottom-left corner of the page.
y (float) – Centre, in cm from the bottom-left corner of the page.
radius (float) – Radius in cm.
fill (color, optional) – Fill colour. Default (or
'none'): not filled.color (color, optional) – Outline colour, or
'none'for no outline. Default: black.linewidth (float, optional) – Outline width in points. Default: GLE’s line width.
- Return type:
None
Notes
Page drawings are written after every axes, so they sit on top of them, in the order they were added. Writes GLE’s
circle.Examples
>>> import gleplot as glp >>> fig = glp.figure() >>> fig.circle(2, 3, radius=0.4, fill="red")
- ellipse(x, y, width, height, *, fill=None, color=None, linewidth=None)[source]
Draw an ellipse on the page, outside any axes.
- Parameters:
x (float) – Centre, in cm from the bottom-left corner of the page.
y (float) – Centre, in cm from the bottom-left corner of the page.
width (float) – Diameters along x and y, in cm.
height (float) – Diameters along x and y, in cm.
fill (color, optional) – Fill colour. Default (or
'none'): not filled.color (color, optional) – Outline colour, or
'none'for no outline. Default: black.linewidth (float, optional) – Outline width in points. Default: GLE’s line width.
- Return type:
None
Notes
Writes GLE’s
ellipse. Seecircle()for the drawing order.
- arc(x, y, radius, theta1, theta2, *, color=None, linewidth=None)[source]
Draw a circular arc on the page, outside any axes.
- Parameters:
x (float) – Centre of the circle, in cm from the bottom-left corner of the page.
y (float) – Centre of the circle, in cm from the bottom-left corner of the page.
radius (float) – Radius in cm.
theta1 (float) – Start and end angles in degrees. The arc runs anticlockwise from
theta1totheta2; 0 is three o’clock.theta2 (float) – Start and end angles in degrees. The arc runs anticlockwise from
theta1totheta2; 0 is three o’clock.color (color, optional) – Line colour. Default: black.
linewidth (float, optional) – Line width in points. Default: GLE’s line width.
- Return type:
None
Notes
Writes GLE’s
arc. Seecircle()for the drawing order.
- bezier(x, y, *, color=None, linewidth=None)[source]
Draw a cubic Bézier curve on the page, outside any axes.
- Parameters:
x (sequence of 4 floats) – The start point, the two control points and the end point, in cm from the bottom-left corner of the page.
y (sequence of 4 floats) – The start point, the two control points and the end point, in cm from the bottom-left corner of the page.
color (color, optional) – Line colour. Default: black.
linewidth (float, optional) – Line width in points. Default: GLE’s line width.
- Return type:
None
Notes
Writes GLE’s
bezier. Seecircle()for the drawing order.
- curve(x, y, start_slope, end_slope, *, color=None, linewidth=None)[source]
Draw a smooth curve through points on the page, outside any axes.
- Parameters:
x (sequence of float) – At least two points the curve passes through, in order, in cm from the bottom-left corner of the page.
y (sequence of float) – At least two points the curve passes through, in order, in cm from the bottom-left corner of the page.
start_slope ((float, float)) – Tangent vector
(dx, dy)of the curve at the first and last point. Its length matters as well as its direction: a longer vector carries the curve further that way before it turns.end_slope ((float, float)) – Tangent vector
(dx, dy)of the curve at the first and last point. Its length matters as well as its direction: a longer vector carries the curve further that way before it turns.color (color, optional) – Line colour. Default: black.
linewidth (float, optional) – Line width in points. Default: GLE’s line width.
- Return type:
None
Notes
Writes GLE’s
curve. Seecircle()for the drawing order.
- polygon(x, y, *, fill=None, color=None, linewidth=None)[source]
Draw a closed polygon on the page, outside any axes.
- Parameters:
x (sequence of float) – At least three corners, in order, in cm from the bottom-left corner of the page. The last corner is joined back to the first.
y (sequence of float) – At least three corners, in order, in cm from the bottom-left corner of the page. The last corner is joined back to the first.
fill (color, optional) – Fill colour. Default (or
'none'): not filled.color (color, optional) – Outline colour, or
'none'for no outline. Default: black.linewidth (float, optional) – Outline width in points. Default: GLE’s line width.
- Return type:
None
Notes
Writes a GLE
begin pathblock. Seecircle()for the drawing order.
- table(x, y, s)[source]
Write text on the page with its columns lined up, outside any axes.
- Parameters:
x (float) – Where the text starts, in cm from the bottom-left corner of the page.
y (float) – Where the text starts, in cm from the bottom-left corner of the page.
s (str) – The text. Words separated by more than one space are aligned in columns; a newline starts a row. A row cannot start with the word
beginorend.
- Return type:
None
Notes
Writes a GLE
begin tableblock. The columns line up exactly only in a fixed-pitch font. Seecircle()for the drawing order.
- tex(x, y, s)[source]
Write a block of LaTeX on the page, outside any axes.
- Parameters:
x (float) – Where the text starts, in cm from the bottom-left corner of the page.
y (float) – Where the text starts, in cm from the bottom-left corner of the page.
s (str) – LaTeX source, for example
r"\textbf{Note}". A line cannot start with the wordbeginorend;\begin{...}is fine. The last line cannot hold a%comment.
- Return type:
None
Notes
Writes a GLE
begin texblock, so compiling the figure needs a LaTeX installation that GLE can find. GLE sets the text in one LaTeX box, so a newline insdoes not start a new line in the output; use atabularfor several lines. Seecircle()for the drawing order.
- absolutize_file_references(base_dir)[source]
Rewrite relative data and image paths to absolute paths.
Reference-mode series (
file_series) carry theirdata_fileverbatim into the generateddatacommand, and placed images (Axes.image()) theirfileinto the draw call, 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 – Any other keyword warns and is ignored.
- 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, *, transparent=None, grayscale=False, **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. SVG raisesValueErrorfor a figure whose style hasusetex=True: GLE cannot put LaTeX labels in SVG.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). An'svg'is always compiled with the flag, andFalsewarns: GLE draws SVG through Cairo anyway, and without the flag it leaves out text in a PostScript font.When Cairo ends up active (auto, forced or SVG) and this figure’s configured font (
style’sfont) is not one of GLE’s Cairo-safe fonts, aUserWarningnaming why Cairo is on (the figure’s semi-transparent colours,cairo=Trueor SVG output) is 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) and of GLE’s.gle/LaTeX cache entries that a compiled export otherwise removes fromexport_dirafterwards – see the “Engine intermediates” note below. Default False. Has no effect 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.transparent (bool, optional) – Give a PNG an alpha channel instead of a white background (GLE’s
-transparent).NonemeansFalse. PDF, EPS and SVG output has no background to remove.Truewarns for a JPEG, which has no alpha channel, and for a grayscale PNG compiled without Cairo, which loses it.grayscale (bool, optional) –
gleplot keyword, not a matplotlib one: compile with the colours GLE draws converted to their grey level (GLE’s
-nocolor). A heatmap’s image stays in colour in PDF, EPS and SVG, soTruewarns there for a figure with a heatmap.transparentandgrayscaleact when GLE compiles, so they warn when only the.glescript is saved.folder (bool, optional) – If True, place the exported file, the intermediate
.glescript, and generated data files in a sibling<name>.gleplotdirectory.**kwargs – Additional arguments. matplotlib’s
bbox_inches,pad_inches,facecolorandedgecolorare accepted and warn: the page is alwaysfigsize, and its background is not settable. Any other keyword (metadata,orientation, a misspelt one, …) warns and is ignored.
- 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.LaTeX cache. A figure GLE renders through LaTeX (
tex(), orGLEStyleConfig(usetex=True)) makes GLE write a.gle/cache directory intoexport_dir. A successful compile removes this script’s folder in it and anytexpreamble.*files the compile created, then the directory if it is empty. Preamble files are left if they were already there, or if another figure’s folder is in the cache, since other figures in the same directory share them. Two first-time compiles started together in one directory can still remove a preamble the other is using; give such parallel saves separate directories.keep_intermediates=Truekeeps the cache.
- 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 temporary file, or None when the figure was displayed inline in Jupyter. Nothing is printed; outside a notebook, open the returned path to see the figure. A PDF cannot be shown inline, so in a notebook
format='pdf'warns and returns the path. The.glescript and data files compiled to make the image are removed; only the returned file is left, for the caller to delete.- 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/fill/axvspan/axhspanwithalpha < 1(Axes.fill_between(),Axes.fill(),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.