Axes
- class gleplot.Axes(figure, position=None)[source]
Matplotlib-like axes for plotting.
- Parameters:
position (tuple | None)
- axes_id: str
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. A parsed.glefile has no id to recover, so the recognizer’s freshly constructedAxesobjects get a new one here.- Type:
Stable opaque identity for this 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().
- x2ticklabel_size: float | None
x2 tick labels are off unless
x2labels onis given, the same rule as y2. 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).
- title_font: str | None
GLE font of the graph title and of each axis title (
title ... font F,xtitle ... font F). Set throughfontname=onset_title(),set_xlabel()andset_ylabel().
- xside_color: str | None
Axis-line colour and width (points), GLE
xside color C lwidth W. GLE copies an x or y setting onto x2 or y2, so these also style the opposite edge unless that edge has its own. Set throughset_axis_line().
- xside_off: bool | None
The bottom or left axis line hidden (True, GLE
xside off), its ticks and tick labels kept. None draws it. Set throughset_axis_line(visible=False), which hides the top and right sides through_x2axis_off/_y2axis_off.
- xnticks: int | None
GLE
xaxis nticks N ftick F shift S symticksandxnoticks p1 p2 ....shiftis in cm;symticksis True or None. Set throughset_xticks()andset_yticks().- Type:
Tick placement beyond
dticks
- xtick_length: float | None
GLE
xticks length L lwidth W color Cfor the major ticks and the same onxsubticksfor the minor ones. Lengths and widths are points, the length being matplotlib’s whole tick (GLE draws half of it on each side underxsymticks). Direction is'in','out'or None; GLE writes'out'as a negative length.- Type:
Tick marks, set through
tick_params()
- xminorticks: bool | None
Minor ticks switched on (True,
xsubticks on) or off (False,xsubticks off); None leaves GLE’s default. Set throughminorticks_on()/minorticks_off().
- xnsubticks: int | None
Minor ticks between two major ones (GLE
xaxis nsubticks N) and which sub-decades of a log axis are labelled (GLExlabels log MODE). Set throughset_xticks()/set_yticks().
- math_mode: bool | None
the x and y axes cross at (0, 0) and the top and right axes are hidden. True or None. Set through
set_math_mode().- Type:
GLE math mode (
mathin the graph block)
- plot(x, y, linestyle='-', color=None, marker=None, markersize=6, linewidth=1, label=None, yaxis='y', xaxis='x', offset=0.0, fillstyle=None, markerfacecolor=None, zorder=None, drawstyle=None, line_mode=None, mdist=None, deresolve=None, deresolve_average=False, xmin=None, xmax=None, ymin=None, ymax=None, **kwargs)[source]
Plot line or scatter plot (if marker without line).
- Parameters:
x (array-like) – Data coordinates of the same length, as in matplotlib: a scalar is one point and a single column one line. Other shapes raise
ValueError. A NaN or infinity breaks a drawn line there, as in matplotlib; such a line is not smoothed or thinned.y (array-like) – Data coordinates of the same length, as in matplotlib: a scalar is one point and a single column one line. Other shapes raise
ValueError. A NaN or infinity breaks a drawn line there, as in matplotlib; such a line is not smoothed or thinned.linestyle (str) – Line style:
'-','--',':','-.', matplotlib’s names'solid','dashed','dotted','dashdot', or'none'for no line. Any other string is read as matplotlib’s format string,plot(x, y, 'ro'): a colour letter, a marker character and a line style; acolorormarkerkeyword wins over it, with a warning. PassingNoneasks for matplotlib’s default, a solid line. A dash tuple or any other value warns and is drawn solid.color (str, optional) – Color name or code (‘b’, ‘red’, etc.). Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).marker (str, optional) – Marker symbol (‘o’, ‘s’, ‘^’, etc.) - omit for line only
markersize (float) – Marker size (matplotlib convention, 1-100)
linewidth (float or None) – Line width in points, finite and 0 or more;
Nonemeans the default width. 0 draws no line, aslinestyle='none'does.label (str, optional) – Legend label
yaxis (str, optional) – Which y-axis to use: ‘y’ (left, default) or ‘y2’ (right)
xaxis (str, optional) – Which x-axis to use: ‘x’ (bottom, default) or ‘x2’ (top)
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).
drawstyle (str, optional) –
'default','steps','steps-pre','steps-mid'or'steps-post'.'default'(and omitting it) is a straight polyline. The step styles are GLE line modes:'steps'and'steps-pre'emitline fsteps(matplotlibwhere='pre'),'steps-post'emitsline steps, and'steps-mid'emitsline hist.dsis accepted as an alias (see**kwargs). An unknown value raisesValueError.line_mode ({'steps', 'fsteps', 'hist', 'bar', 'impulses'}, optional) – The GLE line mode itself, for a caller that already speaks GLE.
'impulses'is whatstem()uses;'bar'is GLE’s per-dataset bar outline, notbar(). Must agree withdrawstylewhen both are passed. Omitted, the series stays a plainlineand the script is unchanged.mdist (float, optional) – Draw the markers every
mdistcm along the curve instead of one per data point (GLEmdist). Needs amarker; without one it warns and is dropped. Omitted, a marked line takesGLEMarkerConfig.mdistfrom the figure, and when that isNonetoo every point gets a marker. matplotlib’smarkeveryhas no GLE equivalent: it warns and is ignored.deresolve (int, optional) – Draw one point in every
deresolve(GLEderesolve). GLE keeps the first and last point of a line.deresolve_average (bool, optional) – Draw each window of
deresolvepoints as its mean, at the middle x of the window (GLEderesolve N average). Needsderesolve.xmin (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing: a lone edge at or past the far axis limit, which GLE rejects, or an edge at or below zero on a log axis.xmax (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing: a lone edge at or past the far axis limit, which GLE rejects, or an edge at or below zero on a log axis.ymin (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing: a lone edge at or past the far axis limit, which GLE rejects, or an edge at or below zero on a log axis.ymax (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing: a lone edge at or past the far axis limit, which GLE rejects, or an edge at or below zero on a log axis.**kwargs – Additional matplotlib-compatible arguments.
lw,ls,c,ms,mfcanddsare matplotlib’s short names forlinewidth,linestyle,color,markersize,markerfacecoloranddrawstyle. matplotlib raises for a name passed with its short name; here the full name wins, with a warning, unless it is left at its default.solid_capstyle,dash_capstyle,solid_joinstyleanddash_joinstyletake matplotlib’s values; GLE caps and joins every line in the figure alike, so one that differs from the figure’sGLEStyleConfigline_cap/line_joinwarns and is not applied. Any other keyword (alpha,markeredgecolor, …) warns and is ignored.offset (float)
- Returns:
Line object (for compatibility)
- Return type:
Line2D
- step(x, y, *args, where='pre', **kwargs)[source]
Draw a step plot.
A thin wrapper around
plot()that selects a GLE line mode.wherefollows matplotlib:'pre'(default): the interval(x[i-1], x[i]]has valuey[i]. GLEline fsteps(vertical, then horizontal).'post': the interval[x[i], x[i+1])has valuey[i]. GLEline steps(horizontal, then vertical).'mid': the step is halfway between the x positions, and each point is a bin center. GLEline hist.
A positional format string such as
'r--'is read as byplot(); more positional arguments warn and are ignored.wherewins over an explicitdrawstyle.- Return type:
self
- Parameters:
where (str)
- stem(*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, orientation='vertical', **kwargs)[source]
Draw a stem plot as GLE
line impulses.One positional argument is the y values, with
x = 0 .. n-1. Two arex, y. The stems and their head markers are one GLE dataset, so they share a color. The default head is a filled circle; passmarkerfmt='none'for stems alone.GLE’s impulse origin is not matplotlib’s
bottom. It is 0 when the y range includes 0, otherwise the range edge nearest 0 (the axis range, unless the dataset sets its own). No baseline is drawn.orientation='horizontal'warns and still draws vertical stems.
- hist(x, bins=10, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, **kwargs)[source]
Bin samples and draw the counts.
GLE bins the samples with
let dK = hist dJand stores a point at each bin centre.histtype='step'draws that dataset withline hist.histtype='stepfilled'draws it as adjoining bars of one bin width from zero:fill x1would chord the centres and fill to the axis minimum, which is not the histogram.The drawn heights are counts, matplotlib’s default.
density,weights,cumulative,bottom,stackedandrwidthare accepted and ignored, with a warning.histtype='bar'and'barstacked'warn and are drawn as a step outline; bar gaps and stacks belong to the bar grammar, so they ignoreedgecolorwith a warning.edgecoloris the line colour of a'step'histogram, as in matplotlib, and the bar stroke of a'stepfilled'one;'face'iscolor, and so is a'stepfilled''none', since GLE strokes every bar.alpha=reaches an explicit edge colour; an RGBAcolor’s own alpha does not. Bins are equal width. The window is always written into thelet(data min/max whenrangeis omitted, widened by half a unit when every sample is the same value), so GLE does not re-bin over the axis.Returns this axes. matplotlib’s
(counts, edges, patches)is not available: the counts are computed by GLE at draw time.
- function(expression, xmin=None, xmax=None, step=None, color=None, linestyle='-', linewidth=1, label=None, zorder=None)[source]
Draw a curve that GLE samples from an expression in
x.Written as
let dK = expression from xmin to xmax step step, so the points are computed by GLE and no data file is written. Useplot()when you already have the arrays.- Parameters:
expression (str) – A GLE expression in
x, such as"sin(x)"or"exp(-x^2/2)". It is written as given, without spaces.xmin (float, optional) – The sampled range. Omitted, GLE uses the x axis range; on a polar axes,
xis theta and the range is 0 to 2 pi.xmax (float, optional) – The sampled range. Omitted, GLE uses the x axis range; on a polar axes,
xis theta and the range is 0 to 2 pi.step (float, optional) – Distance between samples. Omitted, GLE takes 100 points. On a log x axis GLE reads
stepas the number of points.color (str, optional) – Line colour. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).linestyle ({'-', '--', ':', '-.'}) – Line style.
linewidth (float) – Line width in points, finite and 0 or more.
label (str, optional) – Legend entry.
- Returns:
This axes.
- Return type:
Notes
gleplot does not evaluate the expression, so
xminandxmaxwiden the x range but nothing widens the y range. Alone on an axes, the curve is scaled by GLE. Beside other data, callset_ylim()if the curve leaves that data’s range. On a polar axes the radial limit is 1 unless data orset_ylim()sets it.
- fit(x, y, expression=None, xmin=None, xmax=None, step=None, color=None, linestyle='-', linewidth=1, label=None, zorder=None, model=None)[source]
Draw the curve GLE fits to
xandy.Give either
expressionormodel. Withexpression, written aslet dK = fit dJ with expression from xmin to xmax step step, GLE finds the coefficients, the names inexpressionother thanx, that fit the data best by least squares. Withmodel, GLE fits one of four curves in closed form with its own routine:modelcurve
GLE routine
"linear"y = a*x+blinfit"exp"y = a*exp(b*x)logefit"exp10"y = a*10^(b*x)log10fit"power"y = a*x^bpowxfitEither way GLE draws the fitted curve. The data itself is not drawn: plot it with
scatter()orplot(). To fit in Python instead, draw the fitted curve withplot().- Parameters:
x (array-like) – The data to fit, of equal length.
y (array-like) – The data to fit, of equal length.
expression (str, optional) – A GLE expression in
x, such as"a*exp(-x/b)+c". It is written as given, without spaces.xmin (float, optional) – The range the fitted curve is drawn over. Omitted, GLE uses the x axis range. Every point is fitted either way.
xmax (float, optional) – The range the fitted curve is drawn over. Omitted, GLE uses the x axis range. Every point is fitted either way.
step (float, optional) – Distance between curve samples. Omitted, GLE takes 100 points. On a log x axis GLE reads
stepas the number of points. Not withmodel: GLE always draws a model at 100 points.color (str, optional) – Line colour. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).linestyle ({'-', '--', ':', '-.'}) – Line style.
linewidth (float) – Line width in points, finite and 0 or more.
label (str, optional) – Legend entry. With
model, it can show the fitted values: see the Notes.model ({'linear', 'exp', 'exp10', 'power'}, optional) – A curve GLE fits in closed form, in place of
expression. It needs points at two or more distinct x."exp"and"exp10"need every y above 0, and"power"every x and y above 0: GLE fits a straight line to their logs.
- Returns:
This axes.
- Return type:
Notes
GLE starts every coefficient of an
expressionat 0, and keeps the fitted values to itself, so they cannot be read back in Python. To start from other values, or to use the fitted ones, fit in Python and draw the curve withplot().With
model, the label can show what GLE fitted. Each of these placeholders is replaced by a number when GLE draws the legend:"linear":{slope}(a),{offset}(b) and{rsq};"exp","exp10"and"power":{prefactor}(a),{exponent}(b) and{rsq}.
{rsq}is the r-squared of the fit. Add:.Nffor N decimal places or:.Nefor scientific notation, the same format specs as in Python:label="slope {slope:.2f}, r$^2$ {rsq:.3f}". Such a legend is drawn after the graph, as forbbox_to_anchor, because GLE fits the data only once the graph is drawn. A placeholder of another model, another format, or a"in a label with a placeholder raisesValueError.In a hand-written
let dK = logefit dJ s o r(and the same forlog10fitandpowxfit), GLE stores the exponentbin the first variable and the prefactorain the second, the other way round from what the GLE manual says.The data bounds the x and y ranges, as for
plot(), andxminandxmaxwiden the x range.
- derived(expression, sources, xmin=None, xmax=None, step=None, nsteps=None, where=None, range=None, color=None, linestyle='-', linewidth=1, label=None)[source]
Draw a curve GLE computes from other series on this axes.
Written as
let dK = expression, in whichd1…dnstand forsources[0]…sources[n-1]; gleplot puts in the names it gives those series. GLE takes the x values of every source, reads each source’s y at those x (interpolating between its points where it has none), and evaluates the expression there. Unless the sources share their x values, none may repeat an x value. The numbers stay inside GLE, so this also works on series read from a file withline_from_file():ax.line_from_file("run1.dat", 1, 2) ax.line_from_file("run2.dat", 1, 2) a, b = ax.file_series ax.derived("d1-d2", [a, b], label="difference")
- Parameters:
expression (str) – A GLE expression in
xandd1…dn, such as"d1-d2"or"(d1+d2)/2". It is written without spaces.sources (series or list of series) – The series
d1…dnstand for, at most 10, each used inexpressionorwhere. Each is a line, scatter, file line, function or fit series of this axes, taken fromax.lines,ax.scatters,ax.file_series,ax.functionsorax.fits. A source with anoffsetis read without it.xmin (float, optional) – Also compute the curve at x values from
xmintoxmax.xmax (float, optional) – Also compute the curve at x values from
xmintoxmax.step (float, optional) – Distance between those extra x values.
nsteps (int, optional) – The number of points from
xmintoxmax, in place ofstep.where (str, optional) – Keep only the points where this GLE expression is true, such as
"d1>0"or"(x>1)and(x<5)". Written without spaces.range (series or list of series, optional) – Compute the curve only at the x values of these series, taken from the same lists as
sources. Omitted, every source’s x values are used.color (str, optional) – Line colour. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).linestyle ({'-', '--', ':', '-.'}) – Line style.
linewidth (float) – Line width in points, finite and 0 or more.
label (str, optional) – Legend entry.
- Returns:
This axes.
- Return type:
Notes
The curve is drawn on top of every other data series of the axes, after the series it reads, and against the primary x and y axes, whichever axes its sources use. Only GLE’s single-expression form is written: the parametric
let ds = x-exp, y-expis not.Each source is stored as its list and its position there, such as
ax.lines[1]. Removing or inserting a series before it in that list makes the curve read whichever series then stands there. If a source is hidden or cannot be loaded when the figure is saved, or its position no longer holds a seriesderivedaccepts, the curve is left out with a warning.gleplot does not evaluate the expression, so the curve does not widen the y range. Call
set_ylim()if it leaves the range of the other data.
- 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', xaxis='x', offset=0.0, fillstyle=None, markerfacecolor=None, zorder=None, xmin=None, xmax=None, ymin=None, ymax=None, **kwargs)[source]
Plot data with error bars.
- Parameters:
x (array-like) – Data coordinates of the same length, as for
plot().y (array-like) – Data coordinates of the same length, as for
plot().yerr (scalar, array-like of shape (N,) or (2, N), optional) – Vertical error bar sizes, as in matplotlib: a scalar is the same error for every point,
Nvalues one symmetric error per point, and shape(2, N)(such as a(lower, upper)tuple ofNvalues each) the lower row and the upper row. Any other shape raisesValueError, a pair of scalars for other than two points included.xerr (scalar, array-like of shape (N,) or (2, N), optional) – Horizontal error bar sizes. Same format as yerr.
fmt (str) – matplotlib’s format string: a colour letter, a marker character and a line style, such as
'ko'or'r--'; seeplot().''(the default) is a solid line;'none'draws only the error bars, with no line and no markers, whatevermarkersays.color,markerandlinestylekeywords win over the format.color (str, optional) – Color name or code. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).marker (str, optional) – Marker symbol (‘o’, ‘s’, ‘^’, etc.)
markersize (float) – Marker size (matplotlib convention, 1-100)
linewidth (float or None) – Line width in points, finite and 0 or more;
Nonemeans the default width. 0 draws no line, aslinestyle='none'does.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).
xmin (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn, error bars included, as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing, as forplot().xmax (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn, error bars included, as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing, as forplot().ymin (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn, error bars included, as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing, as forplot().ymax (float, optional) – This series’ own data range (GLE’s
dN xmin ... ymax): it is drawn, error bars included, as if its x axis ran fromxmintoxmaxand its y axis fromymintoymax, and nothing outside that range is drawn. This rescales the series; it is not a clip window. The tick labels keep the axis’ own range, so they no longer read off this series. An omitted edge is the limit of the axis the series is drawn against.xminmust be belowxmax,yminbelowymax. Saving warns where the range draws nothing, as forplot().**kwargs –
linestyle(aliasls) overrides the line stylefmtgives, as in matplotlib, except underfmt='none'.lw,c,msandmfcare matplotlib’s short names forlinewidth,color,markersizeandmarkerfacecolor; the full name wins, with a warning, unless it is left at its default. Any other keyword (ecolor,elinewidth,capthick, …) warns and is ignored.xaxis (str)
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', xaxis='x', fillstyle=None, markerfacecolor=None, skiprows=0, comment=None, max_rows=None, xmin=None, xmax=None, ymin=None, ymax=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;x_col=0uses the row number as x (seeline_from_file()).fillstyle='none'/markerfacecolor='none'(aliasmfc) select an open marker;markerfacecolor='white'selects a white-filled one.skiprows,commentandmax_rowscontrol how GLE reads the file, as forline_from_file(). Adata_fileholding a double quote raisesValueError: GLE cannot load it.xmin,xmax,yminandymaxare the series’ own data range, as forerrorbar().candmsare accepted forcolorandmarkersize, as byerrorbar(); any other keyword warns and is ignored.- Parameters:
data_file (str)
x_col (int)
y_col (int)
yerr_col (int | None)
color (str | None)
marker (str | None)
markersize (float)
label (str | None)
capsize (float | None)
yaxis (str)
xaxis (str)
fillstyle (str | None)
markerfacecolor (str | None)
skiprows (int)
comment (str | None)
max_rows (int | None)
xmin (float | None)
xmax (float | None)
ymin (float | None)
ymax (float | None)
- line_from_file(data_file, x_col, y_col, color=None, linestyle='-', linewidth=1, label=None, yaxis='y', xaxis='x', drawstyle=None, line_mode=None, skiprows=0, comment=None, max_rows=None)[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.x_col=0uses the row number (1, 2, 3, …) as x; when the file’s first column is text, GLE then labels those x positions with it.drawstyleandline_modeare the same line modes asplot().linestyle='none'warns and drops the mode: there is no line for it to qualify. The series is still a line reference; this method has no scatter form.linewidthis in points, finite and 0 or more, andNoneis the default width, as forplot(); 0 draws no line, aslinestyle='none'does.skiprowsskips that many leading lines of the file,commentreplaces GLE’s comment marker!, andmax_rowsstops after that many data rows (comment and blank lines do not count). They are GLE’signore,commentandnumrowsoptions. GLE itself reads a.gzfile, sodata_filemay name one. Adata_fileholding a double quote raisesValueError: GLE cannot load it.
- SCATTER_DEFAULT_S = 20
Default
scattersize, in matplotlib’s points**2.
- scatter(x, y, s=None, c=None, *, color=None, marker=None, label=None, yaxis='y', xaxis='x', markersize=None, fillstyle=None, markerfacecolor=None, zorder=None, cmap=None, vmin=None, vmax=None, norm=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, the same number of each; otherwise
ValueError, as in matplotlib.y (array-like) – Data coordinates, the same number of each; otherwise
ValueError, as in matplotlib.s (float or array-like, optional) – Marker area in points**2 (matplotlib
scatterconvention). Default 20 when neithersnormarkersizeis given. An array gives each point its own size; see Notes.c (array-like or color, optional) – One number per point colours each point through
cmap, as in matplotlib. One colour is the same ascolor; a sequence with one colour per point is drawn as one series per distinct colour. Cannot be combined withcolor.color (str, optional) – Point color. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig). This and every parameter aftercare keyword-only, as in matplotlib.marker (str, optional) – Marker symbol. Omitted or
None, a circle ('o'), as in matplotlib.label (str, optional) – Legend label
yaxis (str, optional) – Which y-axis to use: ‘y’ (left, default) or ‘y2’ (right)
markersize (float or array-like, optional) – Marker diameter in points (matplotlib
Line2D/plot()convention). Takes precedence overs. An array gives each point its own size; see Notes.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.
cmap (str, optional) – Colormap for numeric
c, as forimshow();rainbowis drawn asviridis, with a warning. Default: the figure graph config’sdefault_cmap.vmin (float, optional) – The values given the colormap’s first and last colour. Default: the smallest and largest finite value of
c. A value outside them takes the end colour.vmax (float, optional) – The values given the colormap’s first and last colour. Default: the smallest and largest finite value of
c. A value outside them takes the end colour.norm (optional) – Not supported: colours are always mapped linearly from
vmintovmax. Passing it warns.**kwargs – Passed to
plot(), which ownsmdist,deresolve,deresolve_averageand thexmin/xmax/ymin/ymaxdata range.xaxis (str)
- Return type:
self
Notes
Per-point sizes (a bubble chart) take one value per point, not negative or infinite; a one-element array is a single size. A NaN or masked size leaves that point out, as in matplotlib. GLE’s
mdatascales only a marker drawn by a subroutine, so the script gets aglp_mdata_<marker>sub that draws the built-in marker at each point’s size. The legend marker’s area is halfway between the largest and smallest point’s, as in matplotlib’s legend. Per-point sizes cannot be combined withmdistorderesolve.Per-point colours (numeric
c) work the same way: the script gets aglp_cdata_<marker>_<cmap>sub that draws the built-in marker in each point’s colour. The values are written to the data file as given, and aletmaps them onto the colormap. A point whose value is not finite is left out, as matplotlib leaves it out of the plot and its limits. The legend marker takes the colormap’s last colour. Per-point colours cannot be combined withmdistorderesolve. With per-point sizes as well, the colours are drawn and the sizes are not: every point takes the legend marker’s middle size, with a warning.A colour sequence draws one series per distinct colour, in the order each first appears; only the first carries
label.
- bar(x, height, color=None, label=None, zorder=None, width=None, bottom=None, align='center', edgecolor=None, linewidth=None, linestyle=None, yerr=None, xerr=None, ecolor=None, capsize=None, capsize_cm=None, error_kw=None, **kwargs)[source]
Create a bar chart.
One GLE dataset has one face colour and one edge colour. A colour sequence therefore becomes one series per bar (each its own
bar dN), so the bars keep the positions inx. A grouped chart is two calls with the x of the second shifted by the width, which is what matplotlib does; a hand-writtenbar d1,d2 fill c1,c2is the engine’s own side-by-side form and round-trips as one command.bottomstacks: the bar runs from that baseline tobottom + height(GLEbar dTo from dFrom).edgecoloris the stroke (GLEcolor);linewidthandlinestylearelwidthandlstyle.barhis the horizontal form.- Parameters:
x (array-like) – Bar positions.
height (array-like) – Bar lengths. With
bottom, the top isbottom + height.color (str or sequence, optional) – Face colour. A sequence must have one entry, or one per bar. Omitted: the next colour of the axes’ colour cycle (see
GLEStyleConfig).'none'is GLE’sCLEARfill.facecolor/fc/care aliases.label (str, optional) – Legend label. Emitted as
dN keyafter the bar; the bar fill is the swatch. On a per-bar colour split, only the first bar carries it.width (float, optional) – Bar thickness 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.bottom (float or array-like, optional) – Baseline.
0(matplotlib’s default) draws from zero and is not written. An array must have one value per bar.align ({'center', 'edge'}, optional) – GLE centers every bar on its x value.
'edge'warns and is drawn centered.edgecolor (str or sequence, optional) – Stroke colour (GLE
color). Omitted along withlinewidthandlinestyle, the bar has no edge, as in matplotlib. GLE strokes every bar, so a bar with no edge (also'none',linestyle='none'orlinewidth=0) is stroked with a hairline in the colour under the edge: the fill, or a hatched bar’s face.ecis an alias.linewidth (optional) – Edge width in points and matplotlib linestyle.
lw/lsare aliases. Either one withoutedgecolordraws an edge in GLE’s black, where matplotlib draws none.linestyle (optional) – Edge width in points and matplotlib linestyle.
lw/lsare aliases. Either one withoutedgecolordraws an edge in GLE’s black, where matplotlib draws none.yerr (float or array-like, optional) – Vertical and horizontal errors at the bar tip. A scalar or a length-
nsequence is symmetric. Shape(2, n)is asymmetric: the first row is the minus side, the second the plus side. Shape(2, 1)broadcasts. On a horizontal bar the tip isleft + width;xerrruns along the length. A NaN or masked error leaves that whisker out, as in matplotlib.xerr (float or array-like, optional) – Vertical and horizontal errors at the bar tip. A scalar or a length-
nsequence is symmetric. Shape(2, n)is asymmetric: the first row is the minus side, the second the plus side. Shape(2, 1)broadcasts. On a horizontal bar the tip isleft + width;xerrruns along the length. A NaN or masked error leaves that whisker out, as in matplotlib.ecolor (color or sequence, optional) – Whisker colour. Default black. One colour is one error-bar series; a sequence of different colours is one series per bar.
capsize (float, optional) – Cap width in matplotlib points, written as GLE
errwidth/herrwidth. Omitted, the keyword is left off and GLE draws its own cap (one third of the font height).capsize=0is that same default: GLE treats a zero width as “not given”.capsize_cmis the width in centimetres and wins overcapsize.error_kw (dict, optional) –
ecolor,capsize,capsize_cmandzorderoverride the matching arguments. Any other key is ignored, with a warning. Azorderhere, or on the bar, is raised by0.01so the whisker is drawn above the bar.**kwargs –
hatchis a matplotlib hatch string, or a sequence with one per bar.'/','\'and'x'are GLE’sSHADE,RSHADEandGRIDpatterns; repeated ('//') they are the denserSHADE2,RSHADE2andGRID2. As in matplotlib, the hatch is drawn inedgecolor(black when it is not given or'none') over the face colour. GLE has no other pattern, so any other hatch warns and the bar is solid. Anything else GLE cannot draw is accepted and warned about.zorder (float | None)
capsize_cm (float | None)
- Return type:
self
- barh(y, width, height=None, left=None, align='center', **kwargs)[source]
Horizontal bars. See
bar().widthis the bar length (matplotlib’s second positional) andheightis the thickness. Thickness defaults to GLE’s own derivation, the same asbar()’swidth, not matplotlib’s0.8.leftis the baseline (bar’sbottom).xerrandyerrare the same errors asbar():xerrruns along the length, from the tip.
- fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, color=None, alpha=1.0, label=None, offset=0.0, baseline=None, **kwargs)[source]
Fill between two curves, or from one curve down to an axis.
Two arrays emit GLE’s
fill dA,dB. A scalary2(the default0) is broadcast to a constant second curve, so a curve that crosses the constant still fills on both sides of it.baselineis the axis form instead:"x1"emitsfill x1,dN(the curve to the bottom of the y axis) and"x2"emitsfill dN,x2(to the top). That edge is the axis limit, not y=0.whereselects x intervals. Each contiguous run of True samples that has area becomes its own fill, clipped withxmin/xmax. A run is the samples matplotlib fills between: both ends True, so one isolated True draws nothing.interpolate=Truemoves a clip edge to where the two curves cross beside that run. GLE’s clip is a rectangle, so anxthat turns around or repeats a value cannot be expressed that way and the mask is ignored, with a warning.stepis accepted and ignored:fillhas no step mode.xmin,xmax,yminandymaxkeywords are that same clip in data coordinates, not axes fractions. On anx1fill,yminis also the line the region closes on. Passingwheretogether withxminorxmaxraisesValueError.alphabelow 1 composes anrgba255(...)colour. Rendering it needs GLE’s Cairo device, which the compile pipeline enables.Returns this axes. A mask that fills nothing adds no series.
- fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, color=None, alpha=1.0, label=None, **kwargs)[source]
Fill between two curves
x1(y)andx2(y).The horizontal form of
fill_between(). GLE’s two-curve fill is vertical, so the band is the closed polygonfill dNthatfill()draws:(x1, y)forward, then(x2, y)back. A scalarx2(the default0) is a constant curve. Curves that cross fill on both sides of the crossing, as in matplotlib.whereselects y intervals, as it selects x intervals onfill_between(): each contiguous run of True samples becomes its own polygon, clipped withymin/ymax.interpolate=Truemoves a clip edge to where the two curves cross beside that run.yhas to be finite and strictly monotonic for the mask; otherwise it is ignored, with a warning.stepis accepted and ignored.xmin,xmax,yminandymaxkeywords clip the polygon in data coordinates. Passingwheretogether withyminorymaxraisesValueError.alphabelow 1 composes anrgba255(...)colour, as onfill_between().The model holds the polygon, so a figure read back with
gleplot.open_gle()has afill()series in its place.Returns this axes. A mask that fills nothing adds no series.
- stackplot(x, *args, labels=(), colors=None, baseline='zero', **kwargs)[source]
Stack the curves in
argsas filled bands overx.Each layer is a
fill_between()band from the running sum below it to the running sum including it, so the remaining keywords (alpha,where, …) are passed to every band. An argument may be a 2-D array, one row per layer.- Parameters:
x (array-like) – The shared x values.
*args (array-like) – The layers, bottom first.
labels (sequence of str) – One legend label per layer. Layers past the end have none.
colors (sequence of colors, optional) – Cycled over the layers. Omitted: each layer takes the next colour of the axes’ colour cycle (see
GLEStyleConfig).baseline ({'zero', 'sym', 'wiggle', 'weighted_wiggle'}) – The lower edge of the stack, computed as matplotlib does.
- Returns:
The bands added, bottom first.
- Return type:
list of FillSeries
- Raises:
ValueError – If
baselineis not an accepted value, no layer is given, orcolorsis empty.
Notes
hatchis accepted and ignored, with a warning: a graphfillhas no pattern. The bands read back from a.glefile as separatefill_between()series.
- fill(x, y, *args, color=None, alpha=1.0, label=None, **kwargs)[source]
Fill the polygon with vertices
(x, y).Emits GLE’s
fill dN, which closes the last vertex back to the first. This is not a general path: one polygon, no curves or holes. A third positional argument may be a color (fill(x, y, "b")). Further polygons in the same call are ignored, with a warning.alphabelow 1 is anrgba255(...)colour, as onfill_between().xmin/xmax/ymin/ymaxclip the polygon in data coordinates. GLE fills the interior and does not stroke an edge, soedgecolorandlinewidthare ignored.
- hlines(y, xmin, xmax, colors=None, linestyles='solid', *, label='', **kwargs)[source]
Draw horizontal segments at each
yfromxmintoxmax.Unlike
axhline(), the ends are data coordinates. Seevlines(), which this mirrors, for how the segments are drawn.
- vlines(x, ymin, ymax, colors=None, linestyles='solid', *, label='', **kwargs)[source]
Draw vertical segments at each
xfromymintoymax.Unlike
axvline(), the ends are data coordinates.- Parameters:
x (float or array-like) – Where the segments are.
ymin (float or array-like) – Their ends. A scalar applies to every segment.
ymax (float or array-like) – Their ends. A scalar applies to every segment.
colors (color or sequence of colors, optional) – Cycled over the segments. Default: matplotlib’s
'C0'. Aliascolor.linestyles (str or sequence of str) –
'solid','dashed','dotted','dashdot', their symbols'-','--',':','-.', or'none'(the segment is not drawn), cycled over the segments. Aliaslinestyle/ls.label (str) – Legend label for the whole set. Empty means no legend entry.
**kwargs –
linewidths(aliaslinewidth,lw), in points, a number or one per segment, andzorder. Others warn.
- Returns:
This axes. matplotlib returns a
LineCollection.- Return type:
- Raises:
ValueError – If the ends do not match the positions in length, or a line style is not one of the above.
Notes
The segments are one line dataset per distinct style, with a missing value (
*) between segments so GLE does not join them. The legend entry is on the first of those datasets. A segment with a NaN end is not drawn. A dash pattern given as a tuple warns and is drawn solid. A figure read back withgleplot.open_gle()has aplot()line with NaN gaps in its place.
- 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; a finite number.
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'-.', or matplotlib’s name for one ('dashed', …). A dash tuple or any other value warns and is drawn solid.linewidth (float) – Line width in points, finite and 0 or more.
Noneis the default width; 0 draws no line.label (str, optional) – Legend label.
**kwargs –
lw,lsandcare matplotlib’s short names forlinewidth,linestyleandcolor; the full name wins, with a warning, unless it is left at its default. Any other keyword (alpha,zorder,transform, …) warns and is ignored.
- 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. When the axis it spans has no data and no limit, or its data collapses to one value, it is drawn after the graph instead, above the data; see Reference Lines and Shaded Spans.
- 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.
**kwargs –
facecolor(fc) is accepted forcolor;colorwins, with a warning, when both are given. Any other keyword (edgecolor,hatch,zorder, …) warns and is ignored.
- 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 drawn afterend graphagainstxgmin/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_listdrawn after the graph.- 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_fillsandFigure._write_reflinescheck 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_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 drawn after the graph 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, rotation=None, **kwargs)[source]
Add free-form text annotation in data coordinates or axes fractions.
- Parameters:
x (float) – Data coordinates, or axes fractions with
transform=ax.transAxes.y (float) – Data coordinates, or axes fractions with
transform=ax.transAxes.s (str) – Text to render.
color (str, optional) – Text color.
fontsize (float or str, optional) – Font size in points, or a matplotlib size name (
'small','large', …) relative to the figure’s font size.ha ({'left', 'center', 'right'}, optional) – Horizontal alignment. The alignment point is
(x, y).va ({'top', 'center', 'bottom'}, optional) – Vertical alignment. GLE’s
set justhas those three positions and no separate baseline; anything else warns and uses'center'.bbox (dict, optional) – Filled background behind the text. The supported key is
facecolor(fillis accepted as an alias). The box is GLE’sbegin box fillwith a fixed 0.05 cm pad and no outline. Other keys (edgecolor,linewidth,pad,boxstyle, …) warn and are ignored.rotation (float, optional) – Counter-clockwise rotation in degrees about the alignment point (GLE
begin rotate).0omits the block.transform (optional) –
ax.transAxesreadsxandyas fractions of this axes’ frame:(0, 0)is its bottom-left corner and(1, 1)its top-right, whatever the limits, scale or direction of the axes.ax.transData(or leaving it out) means data coordinates. Any other transform warns and the position is read as data coordinates.**kwargs – Any other matplotlib text keyword warns and is ignored. This is not a general page-drawing API.
Examples
>>> import gleplot as glp >>> fig, ax = glp.subplots() >>> _ = ax.text(0.05, 0.95, "(b)", transform=ax.transAxes, va="top")
- property transAxes: _Transform
Axes fractions, for
text(transform=ax.transAxes).(0, 0)is the bottom-left corner of the frame and(1, 1)the top-right, as in matplotlib.
- property transData: _Transform
the default.
- Type:
Data coordinates, for
text(transform=ax.transData)
- annotate(text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)[source]
Annotate the point
xywithtext, optionally with an arrow.- Parameters:
text (str) – The label.
xy ((float, float)) – The annotated point, in data coordinates. The arrow tip.
xytext ((float, float), optional) – Where the text goes, in data coordinates. Default:
xy(and then no arrow is drawn, as in matplotlib, where it has no length).xycoords (str) – Only
'data'is supported. Any other system warns and the numbers are read as data coordinates.textcoords (str) – Only
'data'is supported. Any other system warns and the numbers are read as data coordinates.arrowprops (dict, optional) –
Draw an arrow from the text to
xy. GLEjoinstarts it at the edge of the text box (0.05 cm pad) and ends it onxy. Axyinside the text’s own box draws the arrow back across the text (matplotlib draws nothing); movexytextclear. Supported keys:arrowstyle:'-','->','<-','<->'(open heads, GLEsimple) and'-|>','<|-','<|-|>'(triangle heads, GLEfilled).'fancy','simple','wedge'warn and draw'-|>'. Withoutarrowstyle(matplotlib’s legacywidth/headwidth/shrinkform) the arrow is'-|>'.color, elseedgecolor/ec, elsefacecolor/fc: the one arrow colour. Default black.linewidth/lw: points. Default: GLE’s currentlwidth.
Other keys (
connectionstyleother than straightarc3,shrinkA/shrinkB,linestyle,alpha, head-size parameters, …) warn and are ignored.annotation_clip (bool, optional) – Not modelled: the annotation is always drawn. Warns if given.
**kwargs – Text keywords, as for
text():color,fontsize,ha,va,rotation,bbox.
- Returns:
The stored annotation (also appended to
self.texts).- Return type:
TextAnnotation
- image(fname, extent)[source]
Place an image file over a rectangle in data coordinates.
Unlike
imshow(), which colours a 2-D array, this draws an existing picture: a micrograph, a photograph, a logo.- Parameters:
fname (str or path-like) – A PNG, JPEG, GIF, TIFF or EPS file. GLE reads it when the figure is compiled; a relative path is read from the folder the
.glescript is saved in.extent ((left, right, bottom, top)) – The rectangle the image is stretched over, in data coordinates.
- Returns:
The stored image entry (also appended to
self.images).- Return type:
PlacedImage
- Raises:
ValueError – If the file extension is not one GLE can place, the path holds a double quote, or
extentis not four finite numbers withleft < rightandbottom < top.TypeError – If
fnameis not a string or path, orextentis not a sequence of numbers.
Notes
The image is drawn behind the grid and the data, and clipped to the axes. Its extent takes part in autoscaling, and on a log axis it must be positive. An EPS file is drawn only when GLE compiles through PostScript: not to SVG, and not with GLE’s Cairo device, which a figure with semi-transparent colours needs.
- rug(x, axis='x', length=0.3, position=None, color='black', linewidth=1.0)[source]
Draw a rug: one short tick on the frame at each value of
x.Matplotlib has no rug; this is gleplot API.
- Parameters:
x (array-like) – The values, in data coordinates along
axis. Must be finite.axis ({'x', 'y'}, default: 'x') –
'x'puts the ticks on a horizontal edge at the x values;'y'on a vertical edge at the y values.length (float, default: 0.3) – Tick length in cm, into the axes from the frame. A negative length points out of the axes, as GLE’s
ticks lengthdoes.position (str, optional) – The frame edge:
'bottom'(the default),'top'or'both'foraxis='x';'left'(the default),'right'or'both'foraxis='y'.color (color, default: 'black')
linewidth (float, default: 1.0) – Line width in points.
- Returns:
The stored
Rug(also appended toself.rugs).- Return type:
Rug
- Raises:
ValueError – For an unknown
axisorposition, non-finite values, a zero or non-finitelength, or alinewidththat is not more than 0.TypeError – For a
lengthorlinewidththat is not a number.
Notes
The rug is drawn after the graph block, above the axes’ other series, by
xrug/yrugfrom GLE’s include library (rugs.gle). Its values are written to a sidecar file like any other series. They widen the autoscaled range of their axis; a value outside an axis range set withset_xlim/set_ylimstill draws its tick, outside the frame. On an inverted axis,'bottom'and'left'are the edges at the axis minimum.
- 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: the first and last grid nodes, wherecontourputs them. 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), or one with_rappended for its reversed form, as in matplotlib. A name GLE has no palette for warns and is drawn with the closest one (see the Palette Gallery in the contour and heatmap guide). 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. A colorbar for this image draws the reversed palette to match.
label (str, optional) – Series label (not drawn by the colormap itself; kept so an application can list the series by name).
- Returns:
The stored heatmap series dict.
- Return type:
Notes
Other matplotlib keywords (
alpha,norm,aspect, …) warn and are ignored: a GLE colormap is opaque and maps colours linearly fromvmintovmax.Zmust be finite and unmasked: GLE’s colormap cannot leave a cell blank, so a NaN, an infinity or a masked cell raisesValueErrorwhere matplotlib leaves the cell transparent. Fill them first, e.g. withnp.ma.filled(Z, value).
- function2d(expression, extent, cmap=None, vmin=0.0, vmax=1.0, pixels=None, invert=False, label=None)[source]
Draw a heatmap that GLE computes from an expression in
xandy.Written as one
colormapline, such ascolormap sin(x)*cos(y) 200 200 zmin -1 zmax 1: GLE evaluates the expression at every pixel, so no data file is written. Useimshow()when you already have the array.- Parameters:
expression (str) – A GLE expression in
xandy, such as"sin(x)*cos(y)"or"exp(-(x^2+y^2)/2)". It is written as given, without spaces.extent ((xmin, xmax, ymin, ymax)) – The region to show. It sets the axis range the way an
imshow()extent does.vmin (float, optional) – The values drawn at the two ends of the colour scale (GLE
zmin/zmax).Noneleaves the clause out, and GLE then uses 0 and 1.vmax (float, optional) – The values drawn at the two ends of the colour scale (GLE
zmin/zmax).Noneleaves the clause out, and GLE then uses 0 and 1.pixels (int or (px, py), optional) – Bitmap resolution, as for
imshow().invert (bool) – Invert the colour mapping. A colorbar for this image draws the reversed palette to match.
label (str, optional) – Series label (not drawn by the colormap itself).
- Returns:
The stored heatmap series dict.
- Return type:
Notes
GLE does not look for the range of the expression’s values, so the colour scale runs from
vmintovmax(0 to 1 by default) rather than from the smallest value to the largest asimshow()does. Set them to the range of your function. Values outside are drawn in the end colours.GLE fills the whole graph with the map. When other data or
set_xlim()widens the axes beyondextent, the map covers that wider range too.
- pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, shading=None, antialiased=False, data=None, pixels=None, label=None, **kwargs)[source]
Colour each cell of a rectangular grid by its value.
Signatures:
pcolormesh(C)orpcolormesh(X, Y, C)withCof shape(ny, nx).XandYare 1-D, or the 2-D arraysnp.meshgridreturns. Their spacing must be uniform: a GLE.zgrid is an extent plus a shape. An irregular grid raises; usetripcolor()for scattered or irregularly gridded data.- Parameters:
alpha (float, optional) – Not supported: a GLE colormap is opaque. Passing it warns.
norm (optional) – Not supported: colours are always mapped linearly from
vmintovmax. Passing it warns.vmin (float, optional) – The values given the colormap’s first and last colour.
Noneuses the data’s range.vmax (float, optional) – The values given the colormap’s first and last colour.
Noneuses the data’s range.colorizer (optional) – Not supported; pass
cmap,vminandvmax. Passing it warns.shading ({'auto', 'flat', 'nearest', 'gouraud'}, optional) –
'flat'takesXandYas the cell edges, one longer thanCalong each axis.'nearest'takes them as the cell centres, the same shape asC, and puts each edge halfway between two centres.'auto'(the default, asNone) picks whichever of the two the shapes fit.'gouraud'warns and is drawn as'nearest'.antialiased (bool) – Not supported: the mesh is drawn as one bitmap.
Truewarns.data (optional) – Not supported; pass the arrays directly. Passing it warns.
pixels (int or (px, py), optional) – Bitmap resolution, as for
imshow(). Each cell edge is drawn to within one of these pixels.label (str, optional) – Series label (not drawn by the colormap itself).
- Returns:
The stored heatmap series dict, which
gleplot.Figure.colorbar()takes as itsmappable.- Return type:
Notes
Like
imshow(), a mesh is the axes’ one heatmap, and its values must be finite: aNaNor a masked value raisesValueError, where matplotlib leaves the cell blank. The mesh’s bitmap runs half a cell past each edge, which the axes frame normally hides; saving warns when the axis limits reach beyond the mesh, or when a log axis puts that half cell at or below zero, where GLE does not draw it. Coordinates that decrease are drawn the same as increasing ones, as in matplotlib.edgecolors='none'and'face'are what is drawn; other keywords (anotheredgecolors,linewidth,zorder, …) warn and are ignored.
- contourf(*args, levels=None, cmap=None, vmin=None, vmax=None, extend='neither', pixels=None, label=None, **kwargs)[source]
Fill the bands between contour levels of gridded data.
Signatures, as in matplotlib:
contourf(Z),contourf(X, Y, Z), and either withlevelsas one more positional argument.XandYgive the grid’s nodes: 1-D, or the 2-D arraysnp.meshgridreturns, uniformly spaced and increasing. Without them the nodes are at0 .. nx - 1and0 .. ny - 1. An irregular grid raises; usetripcolor()for scattered or irregularly gridded data.- Parameters:
levels (int or sequence, optional) – The band edges. An int
npicks aboutnround-number levels spanning the data, the way matplotlib’sMaxNLocatordoes;Noneis7. A sequence is used as given, and must increase.cmap (str, optional) – Palette name, as for
imshow();rainbowis drawn asviridis, with a warning.vmin (float, optional) – The values given the colormap’s first and last colour; each band takes the colour of its middle value. Default: the first and last level.
vmax (float, optional) – The values given the colormap’s first and last colour; each band takes the colour of its middle value. Default: the first and last level.
extend ({'neither', 'min', 'max', 'both'}) – Which side’s values beyond the levels are filled, with the colormap’s end colour. With
'neither'they are white.pixels (int or (px, py), optional) – Bitmap resolution, as for
imshow().label (str, optional) – Series label (not drawn by the colormap itself).
- Returns:
The stored heatmap series dict.
- Return type:
Notes
GLE has no filled contour. A
contourfis a heatmap whose palette sub (glp_contourf<k>) colours each value by the band it falls in. GLE’s colormap smooths the grid with a cubic B-spline first, so a band edge is drawn near its level, not on it. When some edge would land more than one bitmap pixel away (a coarse grid for the number ofpixels), the call warns and the heatmap is drawn smooth, coloured by value between the outer levels. That decision assumes the axis limits are the grid’s extent.Like
imshow(), it is the axes’ one heatmap, and values must be finite: aNaNor a masked value raisesValueError. Values beyond the levels are white withextend='neither', where matplotlib leaves them blank. Other keywords (colors,alpha,norm,hatches, …) warn and are ignored.
- 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 (color or sequence of colors) – Contour line colour.
Nonemeans the default, black. A per-level sequence of differing colours warns and its first entry is used, as forlinewidths.linewidths (float) – Line width (matplotlib points). GLE draws every level as one dataset, so a per-level sequence of differing widths warns and its first entry is used.
linestyles (str) – Line style:
'-','--',':','-.'or matplotlib’s name for one ('dashed', …). A dash tuple or any other value warns and is drawn solid. A per-level sequence warns and its first entry is used, as forlinewidths.clabel (bool) – Draw inline contour labels from the generated
-clabels.dat, withcontour_labelsfrom GLE’scontour.gle(blue text in a white box).clabel_fmt (str) – GLE
format$string for the labels.label (str | None)
- Returns:
The stored contour series dict.
- Return type:
Notes
As in matplotlib,
linewidth(lw) andlinestyle(ls) are accepted forlinewidthsandlinestyles. Other matplotlib keywords (alpha,extent,origin, …) warn and are ignored; passxandyto place the grid.
- 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): the first and last grid nodes, wheretricontour()places them. Default: data bounds.cmap (str | None)
vmin (float | None)
vmax (float | None)
interpolation (str)
invert (bool)
label (str | None)
Notes
Axis limits beyond the extent show up to one node spacing of the edge nodes’ colours, as for
imshow(), and saving warns.The remaining keyword arguments are as for
imshow(); others warn and are ignored.
- 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:
Notes
The remaining keyword arguments are as for
contour(), aliases included; others warn and are ignored.
- set_xlabel(label, axis='x', *, fontdict=None, labelpad=None, loc=None, fontname=None, **kwargs)[source]
Set x-axis label.
- Parameters:
label (str) – Axis label text
axis (str, optional) – Which axis: ‘x’ (bottom, default) or ‘x2’ (top). Another string raises
ValueError. A dict orNonehere is taken as matplotlib’s positionalfontdict.fontdict (dict, optional) – Not supported; warns and is ignored. Pass
fontsizeandcoloras keywords.labelpad (float, optional) – Gap between the label and the tick labels, in points (GLE
xtitle ... dist).Nonekeeps the current gap.loc (str, optional) –
'left','center'or'right'. GLE centres axis titles, so the other two warn.fontname (str, optional) – GLE font for the label, such as
'texcmr'(GLExtitle ... font).Nonekeeps the current font.**kwargs –
fontsize(points, or a name such as'small') andcolor;Nonefor either goes back to the default. Other matplotlib text keywords warn and are ignored.
- set_ylabel(label, axis='y', *, fontdict=None, labelpad=None, loc=None, fontname=None, **kwargs)[source]
Set y-axis label.
- Parameters:
label (str) – Axis label text
axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right). Another string raises
ValueError. A dict orNonehere is taken as matplotlib’s positionalfontdict.fontdict (dict, optional) – Not supported; warns and is ignored. Pass
fontsizeandcoloras keywords.labelpad (float, optional) – Gap between the label and the tick labels, in points (GLE
ytitle ... dist).Nonekeeps the current gap.loc (str, optional) –
'bottom','center'or'top'. GLE centres axis titles, so the other two warn.fontname (str, optional) – GLE font for the label (GLE
ytitle ... font).Nonekeeps the current font.**kwargs –
fontsize(points, or a name such as'small') andcolor;Nonefor either goes back to the default. Other matplotlib text keywords warn and are ignored.
- set_title(label, fontdict=None, loc=None, pad=None, *, fontname=None, **kwargs)[source]
Set subplot title.
- Parameters:
label (str) – Title text
fontdict (dict, optional) – Not supported; warns and is ignored. Pass
fontsizeandcoloras keywords.loc (str, optional) –
'left','center'or'right'. GLE centres the title, so the other two warn.pad (float, optional) – Gap between the title and the top of the axes, in points (GLE
title ... dist).Nonekeeps the current gap.fontname (str, optional) – GLE font for the title (GLE
title ... font).Nonekeeps the current font.**kwargs –
fontsize(points, or a name such as'large') andcolor;Nonefor either goes back to the default. Other matplotlib text keywords warn and are ignored.
- set_axis_line(axis='both', *, color=None, linewidth=None, visible=None)[source]
Set the colour, width and visibility of an axis line (GLE
xside).Only the line is styled; ticks, tick labels and the grid keep their own colour. This is gleplot’s form of matplotlib’s
ax.spines[...].set_color()/.set_linewidth()/.set_visible(), with'x','y','x2'and'y2'for the bottom, left, top and right spines.- Parameters:
axis ({'both', 'x', 'y', 'x2', 'y2'}) – Which axis line.
'both'means x and y.color (color, optional) – Any colour
gleplot.colors.rgb_to_gle()accepts.Nonekeeps the current colour.linewidth (float, optional) – Line width in points.
Nonekeeps the current width.visible (bool, optional) –
Falsehides the line,Trueshows it again.Nonekeeps the current visibility.
- Returns:
self.- Return type:
- Raises:
ValueError – On an unknown
axisor a negativelinewidth.TypeError – If
visibleis not a bool or None.
Notes
GLE copies an x setting onto the top edge and a y setting onto the right edge. So
axis='x'styles the top line too, unlessaxis='x2'gives the top line its own style. Visibility is not copied:visible=Falsehides only the edge it names.Hiding the bottom or left line keeps its ticks and tick labels, as in matplotlib. Hiding the top or right edge also removes the tick marks GLE mirrors there (matplotlib draws none there by default), and with them any top or right scale: a
twiny/twinxscale, ayaxis='y2'series’ numbers, a y2 label.savefigwarns in that case.Examples
The open-frame look of
ax.spines[["top", "right"]].set_visible(False):>>> import gleplot as glp >>> fig, ax = glp.subplots() >>> for side in ("x2", "y2"): ... _ = ax.set_axis_line(side, visible=False)
- set_math_mode(on=True)[source]
Draw the x and y axes through the origin (GLE
math).The x axis is drawn at y = 0 and the y axis at x = 0, with ticks on both sides of each, and the top and right axes are hidden. This is gleplot’s form of matplotlib’s
ax.spines['left'].set_position('zero')andax.spines['bottom'].set_position('zero')with the top and right spines hidden.- Parameters:
on (bool, default: True) –
Falsegoes back to axes framing the plot.- Returns:
self.- Return type:
- Raises:
TypeError – If
onis not a bool.
Notes
Both axes move together; moving only one of them is not supported. A right or top axis that is in use (a
yaxis='y2'series, a y2 or x2 label or limit) is still drawn. Both limits need to include 0: a log axis cannot be drawn this way, and an axis whose crossing point is outside the other’s limits is not shown.savefigwarns in both cases.
- set_xlim(left=<unchanged>, right=<unchanged>, axis='x', *, emit=True, auto=False, xmin=<unchanged>, xmax=<unchanged>)[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.- Parameters:
left (float or None, optional) – Axis limits;
None= auto. An omitted limit keeps its current setting, as in matplotlib.leftmay also be a(left, right)pair. A NaN or infinite limit raisesValueError, as in matplotlib, and a limit that is not a numberTypeError.right (float or None, optional) – Axis limits;
None= auto. An omitted limit keeps its current setting, as in matplotlib.leftmay also be a(left, right)pair. A NaN or infinite limit raisesValueError, as in matplotlib, and a limit that is not a numberTypeError.axis (str, optional) – Which axis: ‘x’ (bottom, default) or ‘x2’ (top); another value raises
ValueError.emit (optional) – Accepted for matplotlib compatibility. gleplot has no limit callbacks or autoscaling state, so
emit=Falseandauto=Truewarn and have no effect.auto (optional) – Accepted for matplotlib compatibility. gleplot has no limit callbacks or autoscaling state, so
emit=Falseandauto=Truewarn and have no effect.xmin (float or None, optional) – matplotlib’s aliases of
leftandright; passing both forms of one limit raisesTypeError.xmax (float or None, optional) – matplotlib’s aliases of
leftandright; passing both forms of one limit raisesTypeError.
- Returns:
left, right – The new limits, as matplotlib;
Noneis automatic.- Return type:
- twiny(axes_class=None, *, delta_zorder=0.0, **kwargs)[source]
Open the top x axis as its own data scale.
The returned view plots against that scale (
xaxis='x2') and shares this axes’ y axis. Limits, log, and the axis label set on the view are the top scale; they do not move the bottom one.- Parameters:
axes_class – Accepted for matplotlib compatibility. GLE’s top axis is part of this graph, not a new axes, so they have no effect and warn.
delta_zorder – Accepted for matplotlib compatibility. GLE’s top axis is part of this graph, not a new axes, so they have no effect and warn.
**kwargs – Accepted for matplotlib compatibility. GLE’s top axis is part of this graph, not a new axes, so they have no effect and warn.
- Returns:
A view of this axes bound to the top scale. It is not an entry of
Figure.axes_list.- Return type:
SecondaryXAxis
- twinx(axes_class=None, *, delta_zorder=0.0, **kwargs)[source]
Open the right-hand y axis as its own data scale.
The returned view plots against that scale (
yaxis='y2') and shares this axes’ x axis. Limits, log, the tick format and the axis label set on the view are the right scale; they do not move the left one.- Parameters:
axes_class – Accepted for matplotlib compatibility. GLE’s right axis is part of this graph, not a new axes, so they have no effect and warn.
delta_zorder – Accepted for matplotlib compatibility. GLE’s right axis is part of this graph, not a new axes, so they have no effect and warn.
**kwargs – Accepted for matplotlib compatibility. GLE’s right axis is part of this graph, not a new axes, so they have no effect and warn.
- Returns:
A view of this axes bound to the right scale. It is not an entry of
Figure.axes_list.- Return type:
SecondaryYAxis
- invert_xaxis()[source]
Draw the x axis the other way round, as matplotlib does.
- Returns:
self.- Return type:
Notes
gleplot inverts an axis by storing its limits in descending order (see
set_xlim()). An automatic limit is replaced by the end of the data plotted so far, so the limits are fixed from then on: data plotted afterwards does not widen the axis. Plot first, then invert. With nothing plotted, this warns and does nothing; callset_xlim(right, left)instead. GLE picks the automatic range of thetwiny()andtwinx()scales itself, so inverting one of those needs its limits set first. GLE cannot invert a log axis, sosavefigwarns and draws one the usual way round.
- invert_yaxis()[source]
Draw the y axis the other way round. See
invert_xaxis().- Returns:
self.- Return type:
- semilogx(*args, **kwargs)[source]
plot()with a log x axis.- Parameters:
*args – Passed to
plot(). matplotlib’sbase,subsandnonpositiveare accepted; GLE draws base-10 decades with its own minor ticks, so any other value warns and has no effect.**kwargs – Passed to
plot(). matplotlib’sbase,subsandnonpositiveare accepted; GLE draws base-10 decades with its own minor ticks, so any other value warns and has no effect.
- Returns:
What
plot()returns.- Return type:
- semilogy(*args, **kwargs)[source]
plot()with a log y axis. Seesemilogx().
- loglog(*args, **kwargs)[source]
plot()with log x and y axes. Seesemilogx().
- set_ylim(bottom=<unchanged>, top=<unchanged>, axis='y', *, emit=True, auto=False, ymin=<unchanged>, ymax=<unchanged>)[source]
Set y-axis limits.
- Parameters:
bottom (float or None, optional) – Axis limits;
None= auto (seeset_xlim()). An omitted limit keeps its current setting, andbottommay be a(bottom, top)pair. A limit that is not a finite number raises, as forset_xlim().top (float or None, optional) – Axis limits;
None= auto (seeset_xlim()). An omitted limit keeps its current setting, andbottommay be a(bottom, top)pair. A limit that is not a finite number raises, as forset_xlim().axis (str, optional) – Which axis: ‘y’ (left, default) or ‘y2’ (right); another value raises
ValueError.emit (optional) – As for
set_xlim().auto (optional) – As for
set_xlim().ymin (float or None, optional) – matplotlib’s aliases of
bottomandtop.ymax (float or None, optional) – matplotlib’s aliases of
bottomandtop.
- Returns:
bottom, top – The new limits, as matplotlib;
Noneis automatic.- Return type:
Notes
On a polar axes these are the radial limits:
bottommust be 0 orNone, andtop, the outer ring, positive orNone.
- set_xticks(ticks=None, labels=None, *, dticks=None, dsubticks=None, nticks=None, ftick=None, shift=None, symticks=None, noticks=None, nsubticks=None, loglabels=None, nofirst=None, nolast=None)[source]
Control x-axis tick placement.
- Parameters:
ticks (sequence of float, optional) – Explicit tick positions (GLE
xplaces). PassingNoneleaves the current setting alone; an empty sequence draws no ticks and no tick labels (GLExticks offandxlabels off). On a log axis the minor ticks stay, as in matplotlib, unlessminorticks_off()was called.labels (sequence of str, optional) – Tick labels (GLE
xnames), one per entry ofticks.dticks (float, optional) – Major tick interval (GLE
dticks).dsubticks (float, optional) – Minor tick interval (GLE
dsubticks).nticks (int, optional) – Number of major ticks (GLE
nticks).ftick (float, optional) – Position of the first major tick (GLE
ftick); the others follow at the tick interval.shift (float, optional) – Move the tick labels along the axis by this many cm (GLE
shift), to label the space between two ticks.symticks (bool, optional) – Draw the ticks both inside and outside the frame (GLE
symticks).Falsegoes back to inside only.noticks (sequence of float, optional) – Positions at which no tick is drawn (GLE
xnoticks). An empty sequence clears them.nsubticks (int, optional) – Number of minor ticks between two major ticks (GLE
nsubticks).dsubtickswins when both are set.loglabels ({'off', 'l1', 'l25', 'l25b', 'n1'}, optional) – Which sub-decades of a log axis get a label (GLE
xlabels log):'off'labels the decades only,'l1'adds 1 to 9,'l25'adds 2 and 5,'l25b'is'l25'with a 1 at each decade, and'n1'labels 1 to 9 without the exponent.nofirst (bool, optional) – Leave out the first or last tick label (GLE
nofirst/nolast), so the labels of two touching plots do not overlap.Falseputs the label back.nolast (bool, optional) – Leave out the first or last tick label (GLE
nofirst/nolast), so the labels of two touching plots do not overlap.Falseputs the label back.
- Return type:
self
- Raises:
ValueError – If
nticksornsubticksis not a positive whole number, orloglabelsis not one of the modes above.
Notes
The keywords from
dtickson are gleplot’s, not matplotlib’s.Noneleaves each setting as it is. GLE copies the x settings onto the top axis.
- set_yticks(ticks=None, labels=None, *, dticks=None, dsubticks=None, nticks=None, ftick=None, shift=None, symticks=None, noticks=None, nsubticks=None, loglabels=None, nofirst=None, nolast=None)[source]
Control y-axis tick placement. See
set_xticks().
- set_xticklabels(labels, *, minor=False, fontdict=None, **kwargs)[source]
Label the x ticks placed by
set_xticks()(GLExnames).- Parameters:
labels (sequence of str) – One label per tick position.
minor (bool) – GLE does not label minor ticks:
Truewarns and does nothing.fontdict – matplotlib text properties. They warn and have no effect; style tick labels with
tick_params()orset_tick_format().**kwargs – matplotlib text properties. They warn and have no effect; style tick labels with
tick_params()orset_tick_format().
- Returns:
self.- Return type:
- Raises:
ValueError – If the number of labels is not the number of tick positions.
- set_yticklabels(labels, *, minor=False, fontdict=None, **kwargs)[source]
Label the y ticks placed by
set_yticks(). Seeset_xticklabels().- Returns:
self.- Return type:
- axis(arg=None, /, *, emit=True, **kwargs)[source]
Get or set the axis limits, or hide the axes, as matplotlib does.
- Parameters:
arg (None, bool, str or sequence of 4 floats) –
Noneonly reads the limits.'off'orFalsecallsset_axis_off(),'on'orTrueset_axis_on().'tight'and'auto'put x and y back on automatic limits, which gleplot fits to the data.'equal','scaled','image'and'square'warn and have no effect; useset_aspect()instead.[xmin, xmax, ymin, ymax]sets the limits.emit (bool) – Accepted for matplotlib compatibility;
Falsewarns, since gleplot has no limit-change callbacks.**kwargs –
xmin,xmax,ymin,ymax: set just those limits.
- Returns:
(xmin, xmax, ymin, ymax);Noneis an automatic limit.- Return type:
- Raises:
ValueError – On an unknown string option, or a NaN or infinite limit.
TypeError – If
argis a sequence of the wrong length, or limit keywords are passed together witharg, or a limit is not a number. Any other keyword warns and is ignored.
Notes
Every limit is checked before any is set, so a call that raises leaves the limits as they were.
- set_aspect(aspect, adjustable=None, anchor=None, share=False)[source]
Fix the ratio of a y unit’s length to an x unit’s, as matplotlib does.
- Parameters:
aspect ({'auto', 'equal'} or float) –
'auto'lets the frame fill its place.'equal'gives a unit the same length on both axes, and a numberamakes a y unitatimes as long as an x unit. On a log axis a unit is a decade.adjustable ({None, 'box', 'datalim'}, optional) – gleplot always adjusts the box;
'datalim'warns.anchor (None, str or (float, float), optional) – gleplot always centres the box in its place; anything but
Noneor'C'warns.share (bool, default: False) –
Truewarns: the aspect is set on this axes only.
- Return type:
None
- Raises:
ValueError – If
aspectis not'auto','equal'or a finite positive number, oradjustableoranchoris not one of matplotlib’s values.TypeError – If
aspectis neither a string nor a number.NotImplementedError – On a polar axes.
Notes
When the figure is saved, the frame is shrunk about its centre until its sides have the ratio the axis limits and the aspect call for. The limits are those the figure is saved with; with no data to set them, the aspect warns and is skipped.
The frame is written into the
.glescript as its rectangle, so a figure opened again withgleplot.open_gle()keeps that rectangle but not the aspect: changing its limits afterwards does not reshape the frame.Examples
>>> import gleplot as glp >>> fig, ax = glp.subplots() >>> ax.set_aspect("equal")
- get_aspect()[source]
The aspect
set_aspect()set:'auto'or a float.'equal'reads back as1.0, and a polar axes, whose units are always equal, as1.0.
- set_facecolor(color)[source]
Fill the area inside the axes frame with
color.- Parameters:
color (color or None) – Any colour gleplot accepts elsewhere; an RGBA colour’s alpha makes it see-through.
None,'none'or an alpha of 0 draws no background, the default.
Notes
Written as GLE’s graph
background, which fills the frame before anything in the graph is drawn. Unlike matplotlib, an axes has no background until this is called, so an inset fromFigure.add_axes()shows what is behind it unless it is given one (facecolor='white'). As in matplotlib, an axes with its frame off (set_axis_off()) draws no background. A polar axes has none either: GLE’s fills the rectangular graph window, not the circle, so this warns there and does nothing.Examples
>>> import gleplot as glp >>> fig, ax = glp.subplots() >>> ax.set_facecolor("whitesmoke")
- set_axis_off()[source]
Hide the axis lines, ticks and tick labels.
The plotted data, the title and the legend stay. Undo with
set_axis_on().- Returns:
self.- Return type:
Notes
Unlike matplotlib, the axis labels stay: a hidden label would not be written to the
.glefile, soopen_gle()could not bring it back. This warns when an axis label is set; remove it withset_xlabel('')/set_ylabel('').
- set_axis_on()[source]
Show the axes again after
set_axis_off().Tick labels come back except where
sharexorshareyhides them on an inner subplot.- Returns:
self.- Return type:
- tick_params(axis='both', **kwargs)[source]
Change the appearance of the tick marks.
- Parameters:
axis ({'x', 'y', 'both'}) – Which axis. GLE draws the x settings on the top axis too, and the y settings on the right one.
**kwargs –
which({‘major’, ‘minor’, ‘both’}, default'major'),reset(bool: go back to GLE’s default ticks first),direction({‘in’, ‘out’, ‘inout’}),lengthandwidth(points), andcolor. Any other matplotlib keyword warns and is ignored.
- Returns:
self.- Return type:
- Raises:
ValueError – On an unknown
axis,whichordirection, or a negativelengthorwidth.
Notes
GLE writes these as
xticks length L lwidth W color Candxsubticks .... GLE’s ticks point into the frame unless told otherwise, and pointing them out needs a length:direction='out'with no length uses matplotlib’s default (3.5 points for major ticks, 2 for minor). Minor ticks with no colour of their own are drawn in the major ticks’ colour.'inout'is GLE’ssymticks, which is one setting for the major and minor ticks of an axis, so it is not taken withwhich='minor'.'in'or'out'for the major ticks turns it off again, and so doesreset.An axis with a grid draws the grid lines in place of its ticks, so these settings are not written for it;
grid()styles them.
- 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) – Number of columns. Emitted as GLE
key separatorbetween entries, packed like matplotlib (column-major, the first columns one entry longer).ncolswins when both are passed. An integer less than 1 raisesValueError. A count larger than the number of entries collapses to one entry per column.ncols (int, optional) – Number of columns. Emitted as GLE
key separatorbetween entries, packed like matplotlib (column-major, the first columns one entry longer).ncolswins when both are passed. An integer less than 1 raisesValueError. A count larger than the number of entries collapses to one entry per column.compact (bool, optional) – GLE’s
compact: draw the line and the marker as one swatch. DefaultFalseomits the token. Not a matplotlib keyword.facecolor (color, optional) – Legend-box fill, emitted as GLE
background.boxcoloris not this: in GLE it strokes the fill swatch, and it warns.bbox_to_anchor (tuple of float, optional) –
(x, y)or(x, y, width, height)in axes fractions, as in matplotlib: theloccorner of the legend sits on that point, or on that corner of the box.(1.02, 1)withloc='upper left'puts the legend beside the graph. Emitted as GLEjustifyandabsolutein abegin keyblock after the graph, measured against the graph GLE drew. Replacesoffset. Likeloc, it applies to this call only: a call without it puts the legend back inside the graph. The page does not grow to fit a legend placed outside the graph.borderpad (float, optional) – Space inside the box, line-swatch length, gap between swatch and text, and gap between columns, in units of the legend font size as in matplotlib. Emitted as GLE
margins,llen,distandcoldistin cm. GLE’sdistis also the gap between a marker and a line swatch.Nonerestores GLE’s own spacing.handlelength (float, optional) – Space inside the box, line-swatch length, gap between swatch and text, and gap between columns, in units of the legend font size as in matplotlib. Emitted as GLE
margins,llen,distandcoldistin cm. GLE’sdistis also the gap between a marker and a line swatch.Nonerestores GLE’s own spacing.handletextpad (float, optional) – Space inside the box, line-swatch length, gap between swatch and text, and gap between columns, in units of the legend font size as in matplotlib. Emitted as GLE
margins,llen,distandcoldistin cm. GLE’sdistis also the gap between a marker and a line swatch.Nonerestores GLE’s own spacing.columnspacing (float, optional) – Space inside the box, line-swatch length, gap between swatch and text, and gap between columns, in units of the legend font size as in matplotlib. Emitted as GLE
margins,llen,distandcoldistin cm. GLE’sdistis also the gap between a marker and a line swatch.Nonerestores GLE’s own spacing.labelcolor (color, optional) – One colour for the text of every entry, emitted as GLE
textcoloron each entry of abegin keyblock after the graph. matplotlib’s'linecolor','markerfacecolor'and'markeredgecolor'and a list of colours warn and are ignored.**kwargs – Any other matplotlib legend keyword (
title,labelspacing, …) has no GLEkeyequivalent 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 or a non-positivelinewidth. Any other keyword warns and is ignored, but turns the grid on, as in matplotlib.
Notes
On a polar axes the polar grid is always drawn in its own style:
grid(True)does nothing, and hiding or styling it warns.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', 'x2'}) – Which axis to apply it to.
'both'means x and y (not y2 or x2, which are distinct axes with their own data ranges).
- 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 on/x2labels onis given, so settingaxis='y2'oraxis='x2'also turns them on at write time – seegleplot.writer.GLEWriter.add_axes().
- 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:
Notes
Each series is rebuilt as its
gleplot.seriesclass, whoseARRAY_FIELDSsay which values are restored tofloatnumpy arrays; optional error arrays that wereNonestayNone. All style keys, labels and thedata_filenames are restored verbatim, as are any keys the class does not declare (a project written by a newer gleplot still round-trips).