Gallery
Every example in the examples directory, with the figure it draws and its
code. Each one is a function that saves a .gle script to the current
directory; examples/run_and_compile.py runs them all and compiles the
figures shown here into examples/outputs/ (GLE required):
python examples/run_and_compile.py
Basic Line Plot
Sine and cosine as two line series. Given no colour, they take C0 and C1 from the axes’ colour cycle, as in matplotlib.
Code
def example_basic_line_plot():
print("Creating example: Basic line plot...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Create data
x = np.linspace(0, 2 * np.pi, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Plot: no color given, so each line takes the next colour of the cycle
ax.plot(x, y_sin, label="sin(x)", linestyle="-")
ax.plot(x, y_cos, label="cos(x)", linestyle="--")
# Labels and title
ax.set_xlabel("x (radians)")
ax.set_ylabel("y")
ax.set_title("Sine and Cosine Functions")
ax.legend()
# Save
fig.savefig("example_basic_line_plot.gle")
print(" ✓ Saved to example_basic_line_plot.gle")
Source: examples/basic/line_plots.py
Scatter Plot
Scatter of random data with a linear trend line fitted to it.
Code
def example_scatter_plot():
print("Creating example: Scatter plot...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Create random data
np.random.seed(42)
n = 50
x = np.random.randn(n)
y = 2 * x + np.random.randn(n) * 0.5
# Scatter plot
ax.scatter(x, y, color="blue", s=20, marker="o", label="Data points")
# Add trend line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
x_line = np.linspace(x.min(), x.max(), 100)
ax.plot(x_line, p(x_line), color="red", linestyle="--", label="Trend")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Scatter Plot with Trend Line")
ax.legend()
fig.savefig("example_scatter_plot.gle")
print(" ✓ Saved to example_scatter_plot.gle")
Source: examples/basic/scatter_plots.py
Bar Chart
Bar chart of categorical data, one colour per bar.
Code
def example_bar_chart():
print("Creating example: Bar chart...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Data
categories = np.array([1, 2, 3, 4, 5])
values = np.array([10, 24, 36, 18, 7])
colors = ["red", "blue", "green", "orange", "purple"]
# Bar chart
ax.bar(categories, values, color=colors, label="Values")
ax.set_xlabel("Category")
ax.set_ylabel("Value")
ax.set_title("Bar Chart Example")
ax.legend()
fig.savefig("example_bar_chart.gle")
print(" ✓ Saved to example_bar_chart.gle")
Source: examples/basic/bar_charts.py
Polar Plot
A polar axes from add_subplot(projection='polar').
plot takes theta in radians and the radius; function draws the
rose r = cos(2 theta) from GLE’s own samples. The grid of rings and
spokes, labelled with the angles and radii, replaces the frame, and
set_ylim sets the outer ring.
Code
def example_polar_plot():
print("Creating example: Polar Plot...")
theta = np.linspace(0, 2 * np.pi, 200)
fig = glp.figure(figsize=(6, 4.5))
ax = fig.add_subplot(projection="polar")
ax.plot(theta, 1 + 0.5 * np.cos(3 * theta), label="lobes")
ax.function("cos(2*x)", color="C1", linestyle="--", label="rose")
ax.set_ylim(0, 2)
ax.set_title("Polar curves")
ax.legend(loc="upper right")
fig.savefig_gle("example_polar_plot.gle")
print(" Saved to example_polar_plot.gle")
Source: examples/basic/polar_plots.py
Symmetric Error Bars
Symmetric vertical error bars showing measurement uncertainty.
Code
def example_symmetric_error_bars():
print("Creating example: Symmetric error bars...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Experimental data with constant uncertainty
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([2.1, 3.9, 6.2, 7.8, 10.1, 12.3, 13.8, 16.2])
ax.errorbar(x, y, yerr=0.5, marker="o", fmt="-", color="blue", label="Measurement")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Distance (m)")
ax.set_title("Symmetric Error Bars")
ax.legend()
fig.savefig("example_symmetric_error_bars.gle")
print(" ✓ Saved to example_symmetric_error_bars.gle")
Source: examples/basic/error_bars.py
Asymmetric Error Bars
Vertical error bars with different lower and upper extents.
Code
def example_asymmetric_error_bars():
print("Creating example: Asymmetric error bars...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
x = np.array([1, 2, 3, 4, 5])
y = np.array([10, 25, 40, 55, 70])
# Different upper and lower error magnitudes
yerr_lower = np.array([2, 3, 4, 5, 3])
yerr_upper = np.array([5, 4, 6, 3, 7])
ax.errorbar(
x,
y,
yerr=(yerr_lower, yerr_upper),
marker="s",
linestyle="none",
color="red",
capsize=4,
label="Asymmetric",
)
ax.set_xlabel("Category")
ax.set_ylabel("Value")
ax.set_title("Asymmetric Error Bars")
ax.legend()
fig.savefig("example_asymmetric_error_bars.gle")
print(" ✓ Saved to example_asymmetric_error_bars.gle")
Source: examples/basic/error_bars.py
Horizontal Error Bars
Horizontal and vertical error bars on the same points.
Code
def example_horizontal_error_bars():
print("Creating example: Horizontal + vertical error bars...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
np.random.seed(42)
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.5, 4.0, 3.5, 5.0, 6.5])
# Vertical and horizontal uncertainties
yerr = np.array([0.4, 0.3, 0.5, 0.3, 0.4])
xerr = np.array([0.2, 0.3, 0.15, 0.25, 0.2])
ax.errorbar(
x,
y,
yerr=yerr,
xerr=xerr,
marker="o",
linestyle="none",
color="blue",
capsize=3,
label="Data ± σ",
)
ax.set_xlabel("X measurement")
ax.set_ylabel("Y measurement")
ax.set_title("Horizontal and Vertical Error Bars")
ax.legend()
fig.savefig("example_horizontal_error_bars.gle")
print(" ✓ Saved to example_horizontal_error_bars.gle")
Source: examples/basic/error_bars.py
Error Bars on Line
Error bars on points joined by a line, with an uncertainty that varies along the curve.
Code
def example_errorbar_with_line():
print("Creating example: Error bars with line...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
x = np.linspace(0, 2 * np.pi, 12)
y = np.sin(x)
# Error varies with the measurement
yerr = 0.1 + 0.1 * np.abs(np.cos(x))
ax.errorbar(
x,
y,
yerr=yerr,
marker="o",
fmt="-",
color="green",
capsize=3,
label="sin(x) ± δ",
)
ax.set_xlabel("x (radians)")
ax.set_ylabel("sin(x)")
ax.set_title("Error Bars on Line Plot")
ax.legend()
fig.savefig("example_errorbars_line.gle")
print(" ✓ Saved to example_errorbars_line.gle")
Source: examples/basic/error_bars.py
Combined X+Y Error Bars
Simultaneous horizontal and vertical error bars (uncertainty in both axes), overlaid with a fitted curve.
Code
def example_combined_errorbars():
print("Creating example: Combined X and Y error bars...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Calibration data with uncertainty in both axes
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([1.8, 4.2, 9.1, 16.3, 24.8])
xerr = np.array([0.15, 0.20, 0.10, 0.25, 0.18])
yerr = np.array([0.3, 0.5, 0.6, 0.8, 1.0])
ax.errorbar(
x,
y,
yerr=yerr,
xerr=xerr,
fmt="o",
color="blue",
capsize=4,
label="Measured",
)
x_fit = np.linspace(0.5, 5.5, 100)
ax.plot(x_fit, x_fit**2, color="red", linestyle="--", label="y = x\u00b2")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Combined X and Y Error Bars")
ax.legend()
fig.savefig("example_combined_errorbars.gle")
print(" ✓ Saved to example_combined_errorbars.gle")
Source: examples/basic/error_bars.py
Heatmap (imshow)
imshow of a gridded 2-D Gaussian with a contour overlay and a colorbar.
A single add_subplot(111) axes – the canonical form. gleplot reserves
room to the right of the graph for the colorbar automatically, so the bar,
its tick numbers and its rotated label are not clipped at the page edge.
Code
def example_heatmap_imshow():
print("Creating example: Heatmap (imshow)...")
nx, ny = 120, 100
x = np.linspace(-3, 3, nx)
y = np.linspace(-2.5, 2.5, ny)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X**2 + Y**2) / 2.0)
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Gridded heatmap. origin='lower' (the default) puts row 0 of Z at ymin,
# matching np.meshgrid's row-0-is-y[0] layout, so no flipping is needed.
ax.imshow(Z, extent=(x[0], x[-1], y[0], y[-1]), cmap="viridis")
# Contour lines traced on the same grid, drawn on top of the heatmap.
ax.contour(x, y, Z, levels=6, colors="white", linewidths=0.7)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("2-D Gaussian (imshow + contour)")
fig.colorbar(label="amplitude")
fig.savefig_gle("example_heatmap_imshow.gle")
print(" Saved to example_heatmap_imshow.gle")
Source: examples/basic/heatmap_imshow.py
Placed Image
image places a PNG over a rectangle given in data coordinates.
The picture (here a made-up micrograph) is drawn under the grid and the
data, and clipped to the axes; a line profile is plotted over it.
Code
def example_placed_image():
print("Creating example: Placed Image...")
# A stand-in for a micrograph: soft blobs on a dark background.
yy, xx = np.mgrid[0:120, 0:240]
rng = np.random.default_rng(3)
grey = np.zeros(xx.shape)
for cx, cy, r in zip(rng.uniform(0, 240, 25), rng.uniform(0, 120, 25), [14] * 25):
grey += np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * r**2))
grey = (255 * grey / grey.max()).astype(np.uint8)
_write_png("example_placed_image_micrograph.png", np.dstack([grey] * 3))
x = np.linspace(0, 10, 50)
fig = glp.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
# A relative path is read from the folder the .gle script is saved in.
ax.image("example_placed_image_micrograph.png", extent=(0, 10, 0, 5))
ax.plot(x, 2.5 + 1.5 * np.sin(x), color="orange", linewidth=2)
ax.set_xlabel("x (um)")
ax.set_ylabel("y (um)")
ax.set_title("Line profile over a micrograph")
fig.savefig_gle("example_placed_image.gle")
print(" Saved to example_placed_image.gle")
Source: examples/basic/placed_image.py
Fill Between
Shaded uncertainty band around a central line.
Code
def example_fill_between():
print("Creating example: Fill between...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Create data
x = np.linspace(0, 2 * np.pi, 100)
y_upper = np.sin(x) + 0.5
y_lower = np.sin(x) - 0.5
# Fill between
ax.fill_between(x, y_lower, y_upper, color="lightblue", alpha=0.5, label="±0.5")
# Plot center line
ax.plot(x, np.sin(x), color="blue", label="sin(x)")
ax.set_xlabel("x (radians)")
ax.set_ylabel("y")
ax.set_title("Fill Between Curves")
ax.legend()
fig.savefig("example_fill_between.gle")
print(" ✓ Saved to example_fill_between.gle")
Conditional Fill Between
Fill regions coloured differently depending on which curve is on top,
using the where= parameter.
Code
def example_fill_between_conditional():
print("Creating example: Conditional fill between...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Fill above/below zero differently
ax.fill_between(
x, y1, y2, where=(y1 >= y2), color="lightblue", alpha=0.5, label="sin ≥ cos"
)
ax.fill_between(
x, y1, y2, where=(y1 < y2), color="lightcoral", alpha=0.5, label="sin < cos"
)
ax.plot(x, y1, color="blue", linewidth=2, label="sin(x)")
ax.plot(x, y2, color="red", linewidth=2, linestyle="--", label="cos(x)")
# Mark intersection points
intersections_x = [np.pi / 4, 5 * np.pi / 4]
intersections_y = [np.sin(np.pi / 4), np.sin(5 * np.pi / 4)]
ax.scatter(
intersections_x,
intersections_y,
color="black",
marker="o",
s=80,
label="Intersections",
)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Conditional Fill Between")
ax.legend()
ax.set_xlim(0, 10)
fig.savefig("example_fill_between_conditional.gle")
print(" ✓ Saved to example_fill_between_conditional.gle")
Log Scale
Log-log plot of a power-law relationship.
Code
def example_log_scale():
print("Creating example: Log scale...")
fig = glp.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
# Data that works well with log scale
x = np.logspace(0, 3, 50) # 10^0 to 10^3
y = x**2
# Plot
ax.plot(x, y, color="blue", marker="o", linestyle="-", label="y = x²")
# Set log scales
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("x (log scale)")
ax.set_ylabel("y (log scale)")
ax.set_title("Log-Log Plot")
ax.legend()
fig.savefig("example_log_scale.gle")
print(" ✓ Saved to example_log_scale.gle")
Source: examples/advanced/log_scale.py
Combined Plot
Lines, scatter, and fill_between combined in a single axes.
Code
def example_combined_plot():
print("Creating example: Combined plot types...")
fig = glp.figure(figsize=(10, 7))
ax = fig.add_subplot(111)
# Data
x = np.linspace(0, 10, 50)
y_line = 0.5 * x + 2
y_upper = y_line + np.random.randn(len(x)) * 0.5 + 0.5
y_lower = y_line - np.random.randn(len(x)) * 0.5 - 0.5
# Fill between (background)
ax.fill_between(x, y_lower, y_upper, color="lightgreen", alpha=0.3)
# Plot line
ax.plot(x, y_line, color="darkgreen", linewidth=2, label="Linear fit")
# Scatter points
np.random.seed(42)
x_scatter = np.random.uniform(0, 10, 20)
y_scatter = 0.5 * x_scatter + 2 + np.random.randn(20) * 1.5
ax.scatter(x_scatter, y_scatter, color="red", marker="o", s=30, label="Data points")
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.set_title("Combined Plot: Lines, Scatter, and Fill")
ax.legend(loc="upper left")
ax.set_xlim(-0.5, 10.5)
fig.savefig("example_combined_plot.gle")
print(" ✓ Saved to example_combined_plot.gle")
Multiple Styles
The four line styles and a scatter series in one axes.
Code
def example_multiple_styles():
print("Creating example: Multiple styles...")
fig = glp.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
x = np.linspace(0, 10, 30)
# Different line styles
ax.plot(x, x, color="blue", linestyle="-", label="solid")
ax.plot(x, 2 * x, color="red", linestyle="--", label="dashed")
ax.plot(x, 3 * x, color="green", linestyle=":", label="dotted")
ax.plot(x, 4 * x, color="orange", linestyle="-.", label="dash-dot")
# Scatter with markers
ax.scatter(x[::3], 5 * x[::3], color="purple", marker="o", s=40, label="markers")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Line Styles and Markers")
ax.legend()
fig.savefig("example_multiple_styles.gle")
print(" ✓ Saved to example_multiple_styles.gle")
Side-by-Side Subplots
Two plots side by side in a 1x2 grid.
Code
def example_side_by_side():
print("Creating example: Side-by-side subplots...")
fig, axes = glp.subplots(1, 2, figsize=(14, 6))
x = np.linspace(0, 2 * np.pi, 80)
# Left: sine
axes[0].plot(x, np.sin(x), color="blue", label="sin(x)")
axes[0].set_xlabel("x (radians)")
axes[0].set_ylabel("y")
axes[0].set_title("Sine")
axes[0].legend()
# Right: cosine
axes[1].plot(x, np.cos(x), color="red", label="cos(x)")
axes[1].set_xlabel("x (radians)")
axes[1].set_ylabel("y")
axes[1].set_title("Cosine")
axes[1].legend()
fig.savefig("example_subplots_1x2.gle")
print(" ✓ Saved to example_subplots_1x2.gle")
Source: examples/advanced/subplots.py
Stacked Subplots
Two stacked panels: a fit with error bars on top and its residuals below.
Code
def example_stacked():
print("Creating example: Stacked subplots...")
fig, axes = glp.subplots(2, 1, figsize=(8, 10))
x = np.linspace(0, 10, 60)
# Top: linear data with error bars
y1 = 2 * x + 3 + np.random.default_rng(42).normal(0, 1, len(x))
axes[0].errorbar(
x,
y1,
yerr=1.0,
marker="o",
linestyle="none",
color="blue",
label="Measurements",
)
axes[0].plot(x, 2 * x + 3, color="red", linestyle="--", label="Fit")
axes[0].set_xlabel("x")
axes[0].set_ylabel("y")
axes[0].set_title("Linear Fit with Error Bars")
axes[0].legend()
# Bottom: residuals
residuals = y1 - (2 * x + 3)
axes[1].scatter(x, residuals, color="green", marker="o")
axes[1].set_xlabel("x")
axes[1].set_ylabel("Residual")
axes[1].set_title("Residuals")
axes[1].set_ylim(-4, 4)
fig.savefig("example_subplots_2x1.gle")
print(" ✓ Saved to example_subplots_2x1.gle")
Source: examples/advanced/subplots.py
2x2 Subplot Grid
Four plot types in a 2x2 grid: line, scatter, bar, and asymmetric error bars.
Code
def example_2x2_grid():
print("Creating example: 2x2 subplot grid...")
fig, axes = glp.subplots(2, 2, figsize=(12, 10))
x = np.linspace(0, 2 * np.pi, 50)
# Top-left: line plot
axes[0, 0].plot(x, np.sin(x), color="blue", label="sin")
axes[0, 0].plot(x, np.cos(x), color="red", linestyle="--", label="cos")
axes[0, 0].set_title("Trig Functions")
axes[0, 0].set_xlabel("x")
axes[0, 0].set_ylabel("y")
axes[0, 0].legend()
# Top-right: scatter
np.random.seed(42)
xs = np.random.randn(40)
ys = 0.8 * xs + np.random.randn(40) * 0.3
axes[0, 1].scatter(xs, ys, color="green", marker="o", label="Data")
axes[0, 1].set_title("Correlation")
axes[0, 1].set_xlabel("x")
axes[0, 1].set_ylabel("y")
# Bottom-left: bar chart
categories = np.array([1, 2, 3, 4, 5])
values = np.array([12, 25, 18, 30, 22])
axes[1, 0].bar(categories, values, color="blue")
axes[1, 0].set_title("Bar Chart")
axes[1, 0].set_xlabel("Category")
axes[1, 0].set_ylabel("Count")
# Bottom-right: error bars
xm = np.array([1, 2, 3, 4, 5])
ym = np.array([10, 18, 25, 35, 42])
axes[1, 1].errorbar(
xm,
ym,
yerr=([2, 3, 2, 4, 3], [3, 2, 4, 3, 5]),
marker="s",
linestyle="none",
color="red",
capsize=3,
label="±err",
)
axes[1, 1].set_title("Error Bars")
axes[1, 1].set_xlabel("x")
axes[1, 1].set_ylabel("y")
axes[1, 1].legend()
fig.savefig("example_subplots_2x2.gle")
print(" ✓ Saved to example_subplots_2x2.gle")
Source: examples/advanced/subplots.py
1x3 Comparison
Three panels in a row comparing families of functions.
Code
def example_1x3_comparison():
print("Creating example: 1x3 comparison...")
fig, axes = glp.subplots(1, 3, figsize=(18, 5))
x = np.linspace(0.1, 5, 80)
axes[0].plot(x, x, color="blue", label="y = x")
axes[0].plot(x, x**2, color="red", linestyle="--", label="y = x²")
axes[0].set_title("Polynomial")
axes[0].set_xlabel("x")
axes[0].legend()
axes[1].plot(x, np.log(x), color="green", label="y = ln(x)")
axes[1].plot(x, np.sqrt(x), color="blue", linestyle="--", label="y = √x")
axes[1].set_title("Roots & Logs")
axes[1].set_xlabel("x")
axes[1].legend()
axes[2].plot(x, np.exp(-x), color="red", label="y = e⁻ˣ")
axes[2].plot(x, 1 / x, color="blue", linestyle=":", label="y = 1/x")
axes[2].set_title("Decay Functions")
axes[2].set_xlabel("x")
axes[2].set_ylim(0, 5)
axes[2].legend()
fig.savefig("example_subplots_1x3.gle")
print(" ✓ Saved to example_subplots_1x3.gle")
Source: examples/advanced/subplots.py
Residual Plot Analysis
Measured data and a linear fit above, the residuals below, on a shared x-axis.
Code
def example_residual_plot():
print("Creating example: Data with residuals (shared x-axis)...")
fig, axes = glp.subplots(2, 1, sharex=True, figsize=(10, 8))
# Generate data with a linear trend and scatter
np.random.seed(123)
x = np.linspace(0, 10, 50)
y_true = 2.5 * x + 5
y_measured = y_true + np.random.normal(0, 2, len(x))
# Top: Data with fit
axes[0].scatter(x, y_measured, color="blue", marker="o", label="Measured")
axes[0].plot(
x, y_true, color="red", linewidth=2, linestyle="--", label="Fit: y=2.5x+5"
)
axes[0].set_ylabel("Value")
axes[0].set_title("Linear Regression with Residual Analysis")
axes[0].legend()
# Bottom: Residuals
residuals = y_measured - y_true
axes[1].scatter(x, residuals, color="green", marker="o")
axes[1].plot(x, np.zeros_like(x), color="black", linestyle="--", linewidth=1)
axes[1].set_xlabel("x")
axes[1].set_ylabel("Residual")
axes[1].set_title("Residuals")
fig.savefig("example_residual_analysis.gle")
print(" ✓ Saved to example_residual_analysis.gle")
Source: examples/advanced/shared_axes.py
Secondary Y-Axis
Four figures with a second data set on the right-hand y-axis
(yaxis='y2'): temperature and humidity, two growth curves with a log
scale on the right, voltages and currents in a circuit, and error bars.
Code
def example_secondary_yaxis():
# Example 1: Temperature and Humidity on same plot
print("Creating temperature and humidity plot with secondary y-axis...")
# Generate sample data
days = np.arange(1, 31) # 30 days
temperature = (
20 + 5 * np.sin(2 * np.pi * days / 10) + np.random.randn(30) * 1.5
) # °C
humidity = 60 + 15 * np.cos(2 * np.pi * days / 12) + np.random.randn(30) * 5 # %
fig = glp.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
# Plot temperature on left y-axis (default)
ax.plot(
days, temperature, color="red", linewidth=2, label="Temperature", marker="o"
)
# Plot humidity on right y-axis (y2)
ax.plot(
days,
humidity,
color="blue",
linewidth=2,
label="Humidity",
marker="s",
yaxis="y2",
)
# Configure axes
ax.set_xlabel("Day of Month")
ax.set_ylabel("Temperature (°C)", axis="y")
ax.set_ylabel("Humidity (%)", axis="y2")
ax.set_title("Daily Temperature and Humidity")
# Set y-axis limits
ax.set_ylim(10, 30, axis="y") # Temperature range
ax.set_ylim(30, 90, axis="y2") # Humidity range
ax.legend()
# Save the figure
output_file = "secondary_yaxis_temp_humidity.gle"
fig.savefig_gle(output_file)
print(f"Saved: {output_file}")
# Example 2: Exponential growth with different scales
print("\nCreating exponential growth plot with log scale on y2axis...")
x = np.linspace(0, 5, 50)
y1 = x**2 # Quadratic growth
y2 = np.exp(x) # Exponential growth
fig2 = glp.figure(figsize=(10, 6))
ax2 = fig2.add_subplot(111)
# Plot quadratic on left axis
ax2.plot(x, y1, color="green", linewidth=2, label="Quadratic: x²")
# Plot exponential on right axis with log scale
ax2.plot(x, y2, color="purple", linewidth=2, label="Exponential: eˣ", yaxis="y2")
ax2.set_xlabel("x")
ax2.set_ylabel("x²", axis="y")
ax2.set_ylabel("eˣ", axis="y2")
ax2.set_title("Comparing Growth Rates")
# Set logarithmic scale for y2axis
ax2.set_yscale("log", axis="y2")
ax2.legend()
output_file2 = "secondary_yaxis_growth.gle"
fig2.savefig_gle(output_file2)
print(f"Saved: {output_file2}")
# Example 3: Multiple datasets on each axis
print("\nCreating plot with multiple datasets on each axis...")
t = np.linspace(0, 10, 100)
voltage1 = 5 * np.sin(t)
voltage2 = 3 * np.sin(t + np.pi / 4)
current1 = 2 * np.cos(t)
current2 = 1.5 * np.cos(t - np.pi / 3)
fig3 = glp.figure(figsize=(10, 6))
ax3 = fig3.add_subplot(111)
# Plot voltages on left y-axis
ax3.plot(t, voltage1, color="red", linewidth=2, label="Voltage 1", linestyle="-")
ax3.plot(
t, voltage2, color="darkred", linewidth=2, label="Voltage 2", linestyle="--"
)
# Plot currents on right y-axis
ax3.plot(
t,
current1,
color="blue",
linewidth=2,
label="Current 1",
linestyle="-",
yaxis="y2",
)
ax3.plot(
t,
current2,
color="darkblue",
linewidth=2,
label="Current 2",
linestyle="--",
yaxis="y2",
)
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Voltage (V)", axis="y")
ax3.set_ylabel("Current (A)", axis="y2")
ax3.set_title("AC Circuit: Voltage and Current vs Time")
ax3.legend()
output_file3 = "secondary_yaxis_circuit.gle"
fig3.savefig_gle(output_file3)
print(f"Saved: {output_file3}")
# Example 4: Scatter plot with errorbar on y2axis
print("\nCreating errorbar plot with secondary y-axis...")
x_data = np.array([1, 2, 3, 4, 5])
y_left = np.array([10, 15, 13, 17, 16])
y_right = np.array([100, 120, 110, 130, 125])
yerr_right = np.array([5, 8, 6, 7, 6])
fig4 = glp.figure(figsize=(10, 6))
ax4 = fig4.add_subplot(111)
# Scatter on left axis
ax4.scatter(x_data, y_left, color="orange", s=100, label="Measurement A")
# Errorbar on right axis
ax4.errorbar(
x_data,
y_right,
yerr=yerr_right,
color="teal",
marker="o",
markersize=8,
label="Measurement B",
capsize=5,
yaxis="y2",
)
ax4.set_xlabel("Sample Number")
ax4.set_ylabel("Measurement A (units)", axis="y")
ax4.set_ylabel("Measurement B (units)", axis="y2")
ax4.set_title("Dual-Axis Measurements with Error Bars")
ax4.legend()
output_file4 = "secondary_yaxis_errorbar.gle"
fig4.savefig_gle(output_file4)
print(f"Saved: {output_file4}")
print("\nAll examples created successfully!")
print("\nUsage notes:")
print(
"- Use yaxis='y2' parameter in plot(), scatter(), or errorbar() to plot on right axis"
)
print("- Use ax.set_ylabel(label, axis='y2') to set right axis label")
print("- Use ax.set_ylim(min, max, axis='y2') to set right axis limits")
print("- Use ax.set_yscale('log', axis='y2') to set right axis scale")
Error Bars From File
Error bars drawn from columns of an existing data file, so no extra
.dat file is written.
Code
def example_errorbar_from_file():
print("Creating example: Error bars from file...")
# Create a data file with experimental measurements
data_file = Path("experimental_data.dat")
with open(data_file, "w") as f:
f.write("! Experimental measurements\n")
f.write("! Column map:\n")
f.write("! c1 = Temperature (K)\n")
f.write("! c2 = Resistance (Ohm)\n")
f.write("! c3 = Resistance Error\n")
f.write("! c4 = Voltage (V)\n")
f.write("! c5 = Voltage Error\n")
f.write("!\n")
f.write("! Temp Resistance R_Error Voltage V_Error\n")
# Generate some synthetic data
np.random.seed(42)
temps = np.linspace(100, 400, 10)
for T in temps:
R = 50 + 0.2 * T + np.random.randn() * 2
R_err = 0.5 + np.random.rand() * 0.3
V = 2.0 + 0.005 * T + np.random.randn() * 0.1
V_err = 0.05 + np.random.rand() * 0.02
f.write(f"{T:8.1f} {R:12.3f} {R_err:10.3f} {V:10.3f} {V_err:10.3f}\n")
# Create a figure with two subplots sharing x-axis
fig, axes = glp.subplots(2, 1, figsize=(8, 10), sharex=True)
# Top plot: Resistance vs Temperature (columns 1, 2, 3)
axes[0].errorbar_from_file(
str(data_file),
x_col=1, # Temperature
y_col=2, # Resistance
yerr_col=3, # Resistance error
color="blue",
marker="o",
markersize=5,
capsize=3,
label="Resistance",
)
axes[0].set_ylabel("Resistance (Ω)")
axes[0].set_title("Experimental Data from File")
axes[0].legend()
# Bottom plot: Voltage vs Temperature (columns 1, 4, 5)
axes[1].errorbar_from_file(
str(data_file),
x_col=1, # Temperature
y_col=4, # Voltage
yerr_col=5, # Voltage error
color="red",
marker="s",
markersize=5,
capsize=3,
label="Voltage",
)
axes[1].set_xlabel("Temperature (K)")
axes[1].set_ylabel("Voltage (V)")
axes[1].legend()
fig.savefig("example_errorbar_from_file.gle")
print(" ✓ Saved to example_errorbar_from_file.gle")
print(f" ✓ Data file: {data_file}")
print(" ✓ No additional data_*.dat files generated!")
Dual Axis From File
Two columns of one data file on the left and right y-axes.
Code
def example_dual_axis_from_file():
print("Creating example: Dual axis from file...")
# Create a data file
data_file = Path("climate_data.dat")
with open(data_file, "w") as f:
f.write("! Climate measurements\n")
f.write("! c1=Month c2=Temp(C) c3=T_err c4=Humidity(%) c5=H_err\n")
f.write("!\n")
# Generate synthetic climate data
np.random.seed(123)
for month in range(1, 13):
temp = 15 + 10 * np.sin((month - 4) * np.pi / 6) + np.random.randn()
t_err = 0.5 + np.random.rand() * 0.3
humidity = 65 + 15 * np.cos((month - 1) * np.pi / 6) + np.random.randn() * 2
h_err = 2 + np.random.rand()
f.write(
f"{month:4.0f} {temp:10.2f} {t_err:8.2f} {humidity:12.1f} {h_err:8.2f}\n"
)
# Create figure with dual y-axis
fig = glp.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
# Temperature on left axis (blue)
ax.errorbar_from_file(
str(data_file),
x_col=1,
y_col=2,
yerr_col=3,
color="blue",
marker="o",
markersize=6,
capsize=3,
yaxis="y",
label="Temperature",
)
# Humidity on right axis (red)
ax.errorbar_from_file(
str(data_file),
x_col=1,
y_col=4,
yerr_col=5,
color="red",
marker="s",
markersize=6,
capsize=3,
yaxis="y2",
label="Humidity",
)
ax.set_xlabel("Month")
ax.set_ylabel("Temperature (°C)", axis="y")
ax.set_ylabel("Humidity (%)", axis="y2")
ax.set_title("Climate Data - Dual Axis from File")
ax.legend()
fig.savefig("example_dual_axis_from_file.gle")
print(" ✓ Saved to example_dual_axis_from_file.gle")
print(f" ✓ Data file: {data_file}")
Line Overlay From File
Measured points and a fit line, both read from columns of one data file.
Code
def example_line_overlay_from_file():
print("Creating example: Line overlay from file...")
data_file = Path("fit_results.dat")
with open(data_file, "w") as f:
f.write("! Fit results\n")
f.write("! c1=x c2=y_measured c3=y_err c4=y_fit\n")
f.write("!\n")
np.random.seed(7)
x = np.linspace(0.0, 10.0, 16)
y_fit = 1.5 + 0.7 * x
y_measured = y_fit + np.random.randn(len(x)) * 0.35
y_err = 0.2 + np.random.rand(len(x)) * 0.08
for xi, yi, ei, fi in zip(x, y_measured, y_err, y_fit):
f.write(f"{xi:8.3f} {yi:10.4f} {ei:8.4f} {fi:10.4f}\n")
fig = glp.figure(figsize=(9, 6))
ax = fig.add_subplot(111)
ax.errorbar_from_file(
str(data_file),
x_col=1,
y_col=2,
yerr_col=3,
color="blue",
marker="o",
markersize=5,
capsize=3,
label="Measured",
)
ax.line_from_file(
str(data_file),
x_col=1,
y_col=4,
color="red",
linestyle="--",
linewidth=2,
label="Linear fit",
)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Measured Data with File-Based Fit Overlay")
ax.legend()
fig.savefig("example_line_overlay_from_file.gle")
print(" ✓ Saved to example_line_overlay_from_file.gle")
print(f" ✓ Data file: {data_file}")
Line From File
A model line overlaid on measured points from one existing data file,
without writing a generated data_*.dat file for the line.
Code
def example_line_from_file():
print("Creating example: line_from_file...")
data_file = Path("line_from_file_data.dat")
with open(data_file, "w", encoding="utf-8") as handle:
handle.write("! c1=x c2=y_measured c3=y_error c4=y_model\n")
np.random.seed(21)
x = np.linspace(0.0, 10.0, 18)
y_model = 2.0 + 0.65 * x
y_error = 0.18 + 0.05 * np.random.rand(len(x))
y_measured = y_model + np.random.normal(0.0, y_error)
for xi, yi, ei, mi in zip(x, y_measured, y_error, y_model):
handle.write(f"{xi:8.3f} {yi:10.4f} {ei:8.4f} {mi:10.4f}\n")
fig = glp.figure(figsize=(9, 6))
ax = fig.add_subplot(111)
ax.errorbar_from_file(
str(data_file),
x_col=1,
y_col=2,
yerr_col=3,
color="blue",
marker="o",
markersize=5,
capsize=3,
label="Measured",
)
ax.line_from_file(
str(data_file),
x_col=1,
y_col=4,
color="red",
linestyle="--",
linewidth=2,
label="Model",
)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Line Overlay From Existing Data File")
ax.legend(loc="top left")
fig.savefig("example_line_from_file.gle")
print(" + Saved to example_line_from_file.gle")
print(f" + Data file: {data_file}")
Data Prefix Naming
Sidecar .dat files named by data_prefix on the figure and
data_name on each series.
Code
def example_data_prefix():
print("Creating example: data_prefix naming...")
x = np.linspace(0.0, 1.0, 60)
fig = glp.figure(figsize=(9, 5), data_prefix="experiment_17")
ax = fig.add_subplot(111)
ax.plot(
x, x, color="blue", linewidth=2, label="linear", data_name="Linear Reference"
)
ax.plot(
x,
x**2,
color="red",
linestyle="--",
linewidth=2,
label="quadratic",
data_name="Quadratic Reference",
)
ax.fill_between(
x,
x**2 - 0.04,
x**2 + 0.04,
color="pink",
alpha=0.25,
label="uncertainty",
data_name="Quadratic Uncertainty",
)
ax.set_xlabel("Normalized input")
ax.set_ylabel("Response")
ax.set_title("Custom data_prefix and data_name Output Files")
ax.legend(loc="top left")
fig.savefig("example_data_prefix.gle")
print(" + Saved to example_data_prefix.gle")
print(" + Sidecar .dat files use experiment_17_* or sanitized data_name labels.")
Source: examples/advanced/data_prefix.py
Batch Figure Generation
A loop that writes a batch of related figures.
Code
def example_batch_figures():
print("Creating example: Batch figure generation...")
out_dir = Path("batch_outputs")
out_dir.mkdir(exist_ok=True)
x = np.linspace(0.0, 2.0 * np.pi, 200)
phases = [0.0, np.pi / 6.0, np.pi / 3.0, np.pi / 2.0]
for idx, phase in enumerate(phases, start=1):
fig = glp.figure(figsize=(8, 5), data_prefix=f"batch_{idx}")
ax = fig.add_subplot(111)
y = np.sin(x + phase)
ax.plot(x, y, color="blue", linewidth=2, label=f"phase={phase:.2f}")
ax.set_xlabel("x")
ax.set_ylabel("sin(x + phase)")
ax.set_title(f"Batch Figure {idx}")
ax.legend(loc="top right")
output_file = out_dir / f"example_batch_{idx}.gle"
fig.savefig(str(output_file))
print(f" + Saved {output_file}")
Text Annotations
Text placement, alignment, and boxed labels.
Code
def example_text_annotations():
print("Creating example: Text annotations...")
x = np.linspace(0.0, 10.0, 200)
y = np.sin(x)
fig = glp.figure(figsize=(9, 6))
ax = fig.add_subplot(111)
ax.plot(x, y, color="blue", linewidth=2, label="Signal")
# Mark peak and trough labels with different alignments.
ax.text(
1.57,
1.0,
"Peak",
color="darkblue",
fontsize=11,
ha="center",
va="bottom",
rotation=45,
)
ax.text(4.71, -1.0, "Trough", color="darkred", fontsize=11, ha="center", va="top")
# Add an annotation with a filled background.
ax.text(
7.5,
0.6,
"Window: 7.0 to 8.0 s",
color="black",
fontsize=10,
ha="left",
va="center",
bbox={"facecolor": "white"},
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Amplitude")
ax.set_title("Text Annotation Patterns")
ax.legend(loc="upper right")
fig.savefig("example_text_annotations.gle")
print(" + Saved to example_text_annotations.gle")
Per-Element Styling
Colour, line style, width, and marker set separately on each element of one axes.
Code
def example_per_element_styling():
print("Creating example: Per-element styling...")
x = np.linspace(0.0, 6.0, 80)
fig = glp.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
ax.plot(
x,
np.exp(-0.4 * x),
color="darkblue",
linestyle="-",
linewidth=2.2,
label="Decay A",
)
ax.plot(
x,
np.exp(-0.25 * x),
color="darkgreen",
linestyle="--",
linewidth=1.8,
label="Decay B",
)
ax.plot(
x,
np.exp(-0.15 * x),
color="darkred",
linestyle=":",
linewidth=2.6,
label="Decay C",
)
sample_x = x[::8]
sample_y = np.exp(-0.25 * sample_x)
ax.scatter(
sample_x, sample_y, color="orange", marker="s", s=42, label="Sampled points"
)
band_low = np.exp(-0.25 * x) - 0.08
band_high = np.exp(-0.25 * x) + 0.08
ax.fill_between(
x, band_low, band_high, color="lightgreen", alpha=0.35, label="Tolerance band"
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Response")
ax.set_title("Per-Element Styling in One Axes")
ax.legend(loc="top right")
fig.savefig("example_per_element_styling.gle")
print(" + Saved to example_per_element_styling.gle")
Phase Diagram (tripcolor + tricontour)
Susceptibility phase diagram from scattered data: tripcolor,
tricontour, and a colorbar, with line cuts in a second panel.
Code
def example_phase_diagram():
print("Creating example: Antiferromagnet phase diagram...")
rng = np.random.default_rng(11)
T_N0 = 30.0 # zero-field Neel temperature (K)
Hc = 9.5 # critical field (T)
chi0 = 0.05 # paramagnetic background susceptibility (emu/mol)
amplitude = 1.0 # peak height above background at the transition
n_points = 3200
H = rng.uniform(0.0, 0.92 * Hc, n_points)
T = rng.uniform(1.5, 1.15 * T_N0, n_points)
T_N = T_N0 * np.sqrt(1.0 - (H / Hc) ** 2)
width = 2.0 + 1.4 * (H / Hc) # critical broadening near Hc
chi = chi0 + amplitude * np.exp(-((T - T_N) ** 2) / (2.0 * width**2))
chi += rng.normal(0.0, 0.015 * amplitude, n_points) # measurement noise
fig, axes = glp.subplots(1, 2, figsize=(13, 6))
fig.subplots_adjust(wspace=0.35)
ax = axes[0]
# Scattered-data heatmap: gridded at GLE compile time via `begin fitz`.
# vmax sits just above the physical peak (chi0 + amplitude); the palette
# subs clamp overshoot, so this stays speckle-free (see module docstring).
ax.tripcolor(
T,
H,
chi,
gridsize=(90, 70),
cmap="magma",
vmin=0.0,
vmax=chi0 + 1.15 * amplitude,
)
# Trace the transition boundary near the susceptibility ridge's
# half-height, with inline value labels.
boundary_level = chi0 + 0.55 * amplitude
ax.tricontour(
T,
H,
chi,
gridsize=(90, 70),
levels=[boundary_level],
colors="black",
linewidths=1.3,
clabel=True,
clabel_fmt="fix 2",
)
ax.set_xlabel("Temperature (K)")
ax.set_ylabel("Magnetic field (T)")
ax.set_title("Antiferromagnet Phase Diagram (synthetic data)")
# Greek chi via GLE's TeX-like markup. The '{}' after \chi is required:
# GLE (like TeX) swallows the space right after a macro name, so
# r'\chi (emu ...)' would render as "chi(emu ...)" with no gap.
fig.colorbar(label=r"\chi{} (emu mol^{-1})", format="fix 2")
# Companion panel: susceptibility line cuts at representative fields,
# showing the peak shifting to lower T and broadening as H -> Hc.
ax2 = axes[1]
T_line = np.linspace(1.5, 1.15 * T_N0, 200)
for H_val, color in ((0.0, "blue"), (5.0, "green"), (8.0, "red")):
T_N_line = T_N0 * np.sqrt(1.0 - (H_val / Hc) ** 2)
width_line = 2.0 + 1.4 * (H_val / Hc)
chi_line = chi0 + amplitude * np.exp(
-((T_line - T_N_line) ** 2) / (2.0 * width_line**2)
)
ax2.plot(T_line, chi_line, color=color, linewidth=2, label=f"H = {H_val:.0f} T")
ax2.set_xlabel("Temperature (K)")
# Same label as the colorbar above, but written as matplotlib-style
# mathtext instead of GLE markup -- gleplot translates $...$ segments to
# GLE markup at store time (here to r'\chi{} (emu mol^{-1})'), so both
# styles render identically. Text outside the $...$ passes through.
ax2.set_ylabel(r"$\chi$ (emu mol$^{-1}$)")
ax2.set_title("Susceptibility line cuts")
ax2.set_ylim(0, 1.2)
ax2.legend()
fig.savefig_gle("example_phase_diagram.gle")
print(" Saved to example_phase_diagram.gle")
PRL Fig. 2(a)-style panel
A journal-style single panel on a logarithmic time axis, with fit curves over the data and a background line.
Code
def example_prl_fig2a_style():
rng = np.random.default_rng(20260728)
# Real muSR data are binned uniformly in time; logarithmic sampling keeps
# the marker count reasonable at print size.
t = np.geomspace(0.001, 3.0, 40)
t_model = np.geomspace(0.001, 3.0, 200)
# Only typography here: the line-style numbers come from the library
# defaults, which map '--' and ':' onto the GLE styles that really render
# dashed and dotted.
style = GLEStyleConfig(fontsize=11, default_linewidth=1.1)
# Single-column PRL panel: 3.4 in wide is the journal's column width.
fig = glp.figure(figsize=(3.4, 2.7), dpi=300, style=style, data_prefix="prlfig2a")
fig.subplots_adjust(left=0.17, right=0.98, bottom=0.19, top=0.96)
ax = fig.add_subplot(111)
ax.set_xscale("log")
ax.set_xlim(0.001, 3.0)
ax.set_ylim(0.0, 28.0)
# Background level first, so every marker and fit line sits on top of it.
ax.axhline(A_BG, color="gray", linestyle=":", linewidth=0.9)
for label, color, marker, fill, a_fast, sigma, a_slow, lam in TEMPERATURES:
clean = asymmetry(t, a_fast, sigma, a_slow, lam)
err = np.full_like(t, 0.32)
noisy = clean + rng.normal(0.0, err)
# 'full' -> solid marker; 'none' -> transparent outline;
# 'white' -> outline with an opaque white interior.
face = {"full": None, "none": "none", "white": "white"}[fill]
ax.errorbar(
t,
noisy,
yerr=err,
linestyle="none",
marker=marker,
markersize=3.6,
color=color,
capsize=1.6,
markerfacecolor=face,
label=label,
)
ax.plot(
t_model,
asymmetry(t_model, a_fast, sigma, a_slow, lam),
color=color,
linestyle="--",
linewidth=1.0,
)
ax.set_ylabel("Asymmetry (%)")
ax.set_xlabel("t (\\mu s)")
ax.set_yticks(dticks=5.0)
ax.legend(loc="upper right")
fig.savefig_gle("prl_fig2a_style.gle")
print("Saved: prl_fig2a_style.gle")
return fig
Global Configuration
Defaults changed on GlobalConfig apply to every new figure until
GlobalConfig.reset().
Code
def example_global_config():
print("Example 1: Global Configuration")
print("=" * 50)
# Modify global defaults
# Note: Use GLE font names, not matplotlib names
# Valid GLE fonts: rm (serif), ss (sans-serif), tt (monospace), times8, psb, etc.
print("Setting global font to 'ss' (sans-serif)...")
try:
glp.GlobalConfig.style.font = "ss" # GLE sans-serif font
glp.GlobalConfig.style.fontsize = 12
glp.GlobalConfig.graph.legend_position = "tl"
# Create figure (uses global defaults)
fig = glp.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
x = np.linspace(0, 2 * np.pi, 50)
ax.plot(x, np.sin(x), "b-", label="sin(x)")
ax.plot(x, np.cos(x), "r--", label="cos(x)")
ax.set_xlabel("Angle (radians)")
ax.set_ylabel("Value")
ax.set_title("Global Config Example")
ax.legend()
fig.savefig("example_global_config.gle")
print("✓ Saved to example_global_config.gle\n")
finally:
# Reset so the defaults do not leak into later figures.
glp.GlobalConfig.reset()
Per-Figure Configuration
Two figures with their own GLEStyleConfig and GLEGraphConfig:
one for publication, one for presentation.
Code
def example_per_figure_config():
print("Example 2: Per-Figure Configuration")
print("=" * 50)
# Style for Figure 1: Publication quality
pub_style = glp.GLEStyleConfig(
font="rm", # GLE serif font (Roman)
fontsize=10,
default_linewidth=1.5,
)
pub_graph = glp.GLEGraphConfig(
scale_mode="auto",
legend_position="br",
)
fig1 = glp.figure(figsize=(8, 5), style=pub_style, graph=pub_graph)
ax1 = fig1.add_subplot(111)
x = np.linspace(0, 4 * np.pi, 100)
ax1.plot(x, np.sin(x), "b-", linewidth=1.5, label="Publication style")
ax1.set_xlabel("x")
ax1.set_ylabel("sin(x)")
ax1.set_title("Publication Quality")
ax1.legend()
fig1.savefig("example_publication.gle")
print("✓ Saved to example_publication.gle")
# Style for Figure 2: Presentation quality
pres_style = glp.GLEStyleConfig(
font="ss", # GLE sans-serif font
fontsize=14,
default_linewidth=2.0,
)
pres_graph = glp.GLEGraphConfig(
scale_mode="auto",
legend_position="tl",
)
fig2 = glp.figure(figsize=(10, 6), style=pres_style, graph=pres_graph)
ax2 = fig2.add_subplot(111)
ax2.plot(x, np.cos(x), "r-", linewidth=2.0, label="Presentation style")
ax2.set_xlabel("x")
ax2.set_ylabel("cos(x)")
ax2.set_title("Presentation Quality")
ax2.legend()
fig2.savefig("example_presentation.gle")
print("✓ Saved to example_presentation.gle\n")
Marker Configuration
Default marker and size set with GLEMarkerConfig.
Code
def example_marker_config():
print("Example 3: Marker Configuration")
print("=" * 50)
marker_cfg = glp.GLEMarkerConfig(
default_marker="fsquare", # Filled squares
msize_scale=1.2, # Slightly larger markers
)
fig = glp.figure(figsize=(8, 5), marker=marker_cfg)
ax = fig.add_subplot(111)
x = np.random.rand(30)
y = np.random.rand(30)
ax.scatter(x, y, s=100, color="blue", label="Data points")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Custom Marker Appearance")
ax.legend()
fig.savefig("example_markers.gle")
print("✓ Saved to example_markers.gle\n")
Smooth Curves Configuration
The same data drawn with smooth_curves=True and as a polyline.
Code
def example_smooth_curves():
print("Example 4: Smooth Curves Configuration")
print("=" * 50)
# Figure with smooth curves (opt-in: a spline, not the data)
graph_smooth = glp.GLEGraphConfig(smooth_curves=True)
fig1 = glp.figure(figsize=(8, 4), graph=graph_smooth)
ax1 = fig1.add_subplot(111)
x = [0, 1, 2, 3, 4, 5]
y = [1, 3, 2, 4, 3, 5]
ax1.plot(x, y, "b-", label="Smooth")
ax1.set_title("With Smooth Curves")
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.legend()
fig1.savefig("example_smooth.gle")
print("✓ Saved to example_smooth.gle")
# Figure without smooth curves (the default: a polyline through the points)
graph_sharp = glp.GLEGraphConfig(smooth_curves=False)
fig2 = glp.figure(figsize=(8, 4), graph=graph_sharp)
ax2 = fig2.add_subplot(111)
ax2.plot(x, y, "r-", label="Sharp")
ax2.set_title("Without Smooth Curves")
ax2.set_xlabel("x")
ax2.set_ylabel("y")
ax2.legend()
fig2.savefig("example_sharp.gle")
print("✓ Saved to example_sharp.gle\n")
Custom Line Styles
Line style codes set with GLEStyleConfig.
Code
def example_line_styles():
print("Example 5: Custom Line Styles")
print("=" * 50)
style = glp.GLEStyleConfig(
font="rm", # GLE Roman (serif) font
# GLE's lstyle numbering is not solid/dashed/dotted/dash-dot in
# sequence -- 2 is dotted, 3 dashed, 6 dash-dot. These are the
# library defaults, restated here to show the knob.
line_style_solid=1, # Solid (default)
line_style_dashed=3, # Dashed (default)
line_style_dotted=2, # Dotted (default)
line_style_dashdot=6, # Dash-dot (default)
)
fig = glp.figure(figsize=(10, 5), style=style)
ax = fig.add_subplot(111)
x = np.linspace(0, 4 * np.pi, 100)
ax.plot(x, np.sin(x) + 3, "b-", label="Solid")
ax.plot(x, np.sin(x) + 2, "r--", label="Dashed")
ax.plot(x, np.sin(x) + 1, "g:", label="Dotted")
ax.plot(x, np.sin(x), "m-.", label="Dash-dot")
ax.set_xlim(0, 4 * np.pi)
ax.set_ylabel("f(x)")
ax.set_title("Line Style Examples")
ax.legend(loc="upper right")
fig.savefig("example_line_styles.gle")
print("✓ Saved to example_line_styles.gle\n")