No matching examples. Try another query or clear the filters.
A visual reference · GNU Octave
GNU Octave, one change at a time
From a first calculation to matrices, scientific graphics and a reproducible investigation.
120 original examples in twenty chapters follow a field archive working with synthetic sensor readings. Each complete program runs in a fresh GNU Octave process. Inspect real numerical output, open the actual plots and try one focused change. The readings and their relationships are illustrative. Chapters 13–20 extend the graphical reference with 48 techniques linked to corresponding gnuplot examples.
The Org file is the canonical source. Read the HTML beside your editor,
or download the PDF and sources for offline work.
Last changes: 2026-11-15. Added 48 gnuplot-inspired examples for axes, styles, bars, distributions, multivariate analysis, heatmaps, spatial graphics and model diagnostics.
Read a complete .m program. A parameter table explains the new syntax and units.
Actual result
Inspect native terminal output or a scientific plot produced by Octave and gnuplot.
Try a change
Compare a sibling, edit the downloaded source and run it again with the same setup.
Start at the beginning or use the result gallery, search and topic filters.
Back to example overview returns to the corresponding preview. Every program
starts independently; it does not rely on a previous example or interactive session.
Source-and-input ZIPs retain the local configuration, font and any named CSV input.
Reproduce the examples
The reviewed toolchain is GNU Octave 11.3.0 with the gnuplot 6.0 patchlevel 6
graphics toolkit. No Octave add-on package is required. Install these versions
before building; tools/octave checks them and the local font checksum. Select
another installed Octave binary with OCTAVE=/absolute/path/to/octave-cli.
On the tested macOS system, brew install octave gnuplot poppler installed the
command-line tools; the checked Octave formula is 11.3.0_1. Check octave-cli --version
and gnuplot --version after installation: a future package-manager release may
select a different version. The official 11.3.0 source archive and its checksum
are recorded in VERSIONS.json for installing that exact release on another system.
The shared publisher uses Python 3.14.10, Emacs 31.1 / Org 9.8.7, WeasyPrint 70.0,
PyMuPDF 1.28.2, Pygments 2.21.0 and FontTools 4.66.1. This tour was built with
GNU Make 3.81, Ghostscript 10.08.0, OpenBLAS 0.3.34 and Poppler 26.11.0.
Run make setup in the sibling publisher once for Python dependencies; Emacs,
Octave, gnuplot and Poppler are installed system tools. Builds use no network.
Download the complete reproduction bundle and extract it before
running its commands. It includes every program, shared styling, the local font,
synthetic CSV, license notes and the reproduction driver. Individual source-and-input
ZIPs contain everything local that their program needs. The native tools remain
installation prerequisites; no package is fetched while executing an example.
make full
make test check
tools/octave --version
tools/octave examples/OCT-01-001.m
The driver invokes octave-cli --no-gui --no-window-system --norc --no-history --quiet.
These options avoid graphical windows, personal startup files and persistent history.
A fresh process prevents workspace state leaking between examples. Numeric output
uses an English UTF-8 locale; stochastic programs state their own fixed rng seed.
Plot programs explicitly load config/plot-setup.m. It contains appearance only:
white background, a common blue/orange/green palette, 11-point Source Sans 3 3.052
and a 6 by 3.75 inch page. tools/octave gives the native graphics process the
bundled font through Fontconfig and selects that backend explicitly on macOS.
The plot program writes a real gnuplot/Cairo PDF. Poppler derives SVG with outlined
text and PNG at 120 dpi, preserving the same fonts and geometry. The helper removes
PDF build-date metadata; it does not repair or draw the artwork.
Keep the reviewed numerical runtime single-threaded.
Activate the publisher Python environment before commands that use python3,
or install the bundle's pinned requirements.txt into your own environment.
All displayed results are embedded in the HTML for offline reading; keep companion
folders for individual downloads. Octave and MATLAB share much syntax, but this
tour tests the stated Octave version rather than promising MATLAB compatibility.
Shared graphics setup
% Shared appearance only; no example data or calculation state.warning("off","Octave:gnuplot-graphics");graphics_toolkit("gnuplot");set(0,"defaultfigurevisible","off","defaultfigurecolor",[111]);set(0,"defaultfigurepaperunits","inches","defaultfigurepapersize",[63.75]);set(0,"defaultfigurepaperposition",[0063.75]);set(0,"defaultaxesfontname","Source Sans 3","defaultaxesfontsize",11);set(0,"defaulttextfontname","Source Sans 3","defaulttextfontsize",11);set(0,"defaulttextinterpreter","none");set(0,"defaultlinelinewidth",1.5,"defaultlinemarkersize",5);set(0,"defaultaxescolororder",[0.35.60;.80.30.10;.15.55.40]);
01 · First calculations
Compute a small result, give its inputs names and arrange readings in arrays. The first plot closes the chapter with the same native rendering setup used throughout the tour.
OCT-01-001
Compute an average explicitly
Arithmetic operators combine a few readings into one result. Use parentheses to make the intended grouping visible before introducing array reductions.
Try changing: Reshape the same batch to three rows and two columns.
03 · Array operations and data hygiene
Distinguish elementwise arithmetic from matrix algebra. Apply offsets, summarize dimensions and handle nonfinite values without losing the relationship between readings and their identifiers.
OCT-03-001
Square each measurement independently
Dot operators apply an operation to each entry. Use them when a vector represents independent measurements rather than a matrix transformation.
Matrix multiplication combines rows of the first matrix with columns of the second. Use it for a linear transformation, and compare its result with an elementwise product.
Try changing: Change B(2,1) from 2 to 5 and predict which matrix-product entries change.
OCT-03-003
Broadcast a column calibration
A row of offsets applies one correction per measurement column. Use compatible shapes to express the correction without manually repeating the offsets.
A reduction can summarize sensors or observation times. Use its dimension argument explicitly so an orientation change cannot silently change the question.
Try changing: Reverse the secondary key with [1 -2].
04 · Text and data containers
Keep labels, heterogeneous fields and structured records explicit. Choose a character string, cell array or structure according to the information that must travel together.
OCT-04-001
Build a site label
Formatted text combines a stable identifier with a readable label. Use sprintf when the label should be stored for later output or annotation.
Try changing: Add collection.hour and print it beside the site.
05 · Functions and control flow
Name repeated calculations and make decisions visible. Bound loops, keep function inputs explicit and check the behavior that later analysis depends on.
OCT-05-001
Choose an acceptance outcome
An if statement chooses one output according to the quality condition. Use both branches so an out-of-range observation has an explicit outcome.
Try changing: Replace the loop with 20 .* voltage + 1 and compare the result.
OCT-05-003
Bound a refinement loop
A while loop refines a value until it reaches the tolerance or the iteration limit. Use an explicit budget so an unexpected convergence problem cannot run forever.
Try changing: Add a second argument for the offset.
OCT-05-005
Return two results from a local function
A local helper can return a minimum and a span together. Use this form when both values belong to the same calculation and should share one explicit input.
1;% Mark this complete file as a script before its local helper.function[lowest, span]=reading_limits(values)lowest=min(values);span=max(values)-lowest;endfunction[lowest,span]=reading_limits([12141317]);printf("Minimum: %.1f C; span: %.1f C\n",lowest,span);
Parameter
Meaning in this example
[lowest, span]
Return and receive two values in a defined order.
1;
Keep the file a script with its helper defined before use.
Try changing: Return the maximum as a third output.
OCT-05-006
Check a calibration contract
An assertion makes the expected numerical behavior executable. Use a tolerance for floating-point values and retain a clear success message after the check.
Try changing: Change the gain to 21 and observe the failed contract.
06 · Scientific plotting fundamentals
Choose a visual form that matches the numerical question. Keep units, scales, legends and uncertainty explicit; the shared setup supplies the same page, font and palette for every plot.
OCT-06-001
Compare two sensor runs
Two series on the same axes make their level difference visible. Use a legend with concrete run names and a location that leaves the observations unobscured.
source("config/plot-setup.m");hours=0:4;readings=[1214131716];figure(1);plot(hours,readings,"-o");xlabel("Time (hours)");ylabel("Reading (C)");title("Inspect an observed peak");gridon;axispadded;ylim([1118.5]);text(3,17.4,"Check this peak","horizontalalignment","right");print(gcf,"figures/OCT-06-002.pdf","-dpdfcairo");closeall;
Try changing: Move the note to the reading at hour 1 and revise its wording.
OCT-06-003
Inspect a pairwise relationship
A scatter plot shows paired observations without implying an ordering between neighboring markers. Use it when a voltage and its reference temperature belong to the same sample.
Try changing: Change one reference value and identify its point on the plot.
OCT-06-004
Compare site summaries with bars
Bars compare the three site means on a common baseline. Use explicit site ticks so interpolated numerical positions are not mistaken for additional sites.
source("config/plot-setup.m");sites=1:3;site_mean=[121518.5];figure(1);bar(sites,site_mean);set(gca,"xtick",sites);xlabel("Site identifier");ylabel("Mean reading (C)");title("A summary for each site");gridon;print(gcf,"figures/OCT-06-004.pdf","-dpdfcairo");closeall;
The supplied errors are illustrative one-standard-error values for the three means. Use an uncertainty label and units so the reader does not have to guess what the bars represent.
source("config/plot-setup.m");sites=1:3;site_mean=[121518.5];standard_error=[0.50.70.6];figure(1);errorbar(sites,site_mean,standard_error,"o");set(gca,"xtick",sites);xlabel("Site identifier");ylabel("Mean reading (C)");title("Means with one standard error");gridon;axispadded;print(gcf,"figures/OCT-06-005.pdf","-dpdfcairo");closeall;
Try changing: Double the standard errors while keeping the means fixed.
OCT-06-006
Align two panels on a common scale
Separate panels make each run readable while preserving a fair comparison. Use the same vertical limits so a small change in one panel is not visually exaggerated.
source("config/plot-setup.m");hours=0:4;run_a=[1214131716];run_b=[1113121615];figure(1);subplot(2,1,1);plot(hours,run_a,"-o");ylabel("Run A (C)");title("Runs on a common vertical scale");gridon;axispadded;ylim([1020]);subplot(2,1,2);plot(hours,run_b,"-s");xlabel("Time (hours)");ylabel("Run B (C)");gridon;axispadded;ylim([1020]);print(gcf,"figures/OCT-06-006.pdf","-dpdfcairo");closeall;
Try changing: Change only Run B and confirm that both vertical scales remain identical.
07 · Distributions, fields and surfaces
Select a scale or geometry that reveals the structure in the data. All fields here are small, synthetic and generated locally; no remote map, image or dataset is needed.
OCT-07-001
Inspect exponential decay on a log scale
A logarithmic vertical scale turns this exponential decay into a straight trend. Use it for positive values spanning several orders of magnitude.
source("config/plot-setup.m");hours=linspace(0,10,101);response=exp(-0.5.*hours);figure(1);semilogy(hours,response);xlabel("Time (hours)");ylabel("Normalized response");title("Exponential decay on a logarithmic scale");gridon;print(gcf,"figures/OCT-07-001.pdf","-dpdfcairo");closeall;
Try changing: Change the decay coefficient to 0.8.
OCT-07-002
Show a repeatable distribution
A histogram summarizes the shape of repeated synthetic readings. Use a stated seed so changes in the bin count can be compared against the same observations.
source("config/plot-setup.m");readings=[11121314;14151617;17181920];figure(1);imagesc(readings);axisxy;set(gca,"xtick",1:4,"ytick",1:3);colormap(viridis(128));colorbar;xlabel("Time column");ylabel("Site row");title("Readings (C) by site and time");print(gcf,"figures/OCT-07-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
imagesc
Map the numerical matrix range into colors.
axis xy
Place smaller site indices lower on the vertical axis.
viridis / colorbar
Use one ordered palette and show its numerical range.
Try changing: Raise the middle row by 2 C and inspect the color range.
OCT-07-004
Read a smooth field as contours
Contour bands summarize levels of one synthetic response field. Use this view when the location of equal values matters more than a three-dimensional projection.
source("config/plot-setup.m");[x,y]=meshgrid(linspace(-2,2,31));response=exp(-0.5.*(x.^2+2.*y.^2));figure(1);surf(x,y,response);view(45,30);colormap(viridis(128));xlabel("x");ylabel("y");zlabel("Response");title("A fixed view of the response surface");print(gcf,"figures/OCT-07-005.pdf","-dpdfcairo");closeall;
Try changing: Reverse both components to reverse the circulation.
08 · Linear algebra and numerical reliability
Solve the stated system and inspect the quality of the result. Distinguish an exact solve, a least-squares fit and a low-rank approximation, and keep conditioning separate from residual size.
OCT-08-001
Solve a linear system directly
Left division solves the two coupled equations without explicitly forming an inverse. Use a residual to check that the computed solution satisfies the original system.
Try changing: Raise only the final observation by 1 C.
OCT-08-003
Check the eigenmodes of a symmetric matrix
Eigenvalues describe the action of this symmetric two-state transformation. Use the decomposition residual to verify the returned modes without relying on arbitrary vector signs.
Try changing: Change the two diagonal entries from 2 to 3.
OCT-08-004
Retain one singular component
A truncated singular-value decomposition approximates the matrix with one component. Use its reconstruction error to quantify what the compression removes.
A nearly dependent system can amplify a small input perturbation. Use conditioning and solution change together; a small residual alone does not establish accuracy relative to the unperturbed data.
Try changing: Reduce the perturbation to 0.00001 and compare its effect.
09 · Statistics and calibration
State the quantity being summarized and the assumptions behind an uncertainty measure. These samples are synthetic; fitting and resampling illustrate methods rather than establish properties of a real monitoring network.
OCT-09-001
Distinguish spread from uncertainty of a mean
Sample standard deviation describes observation spread, while standard error summarizes uncertainty of a mean under independent sampling. Use both quantities with their units and sample count.
Try changing: Repeat the observations twice and compare SD with SE.
OCT-09-002
Summarize with empirical quantiles
Quantiles describe the distribution without assuming a normal model. Use the median and interquartile range to retain a summary that is less dominated by a large extreme.
Try changing: Change 21 to 100 and compare the mean with the median.
OCT-09-003
Measure paired linear association
Covariance retains the units and scale of the two variables; correlation standardizes their linear association. Use paired rows so the relationship is not destroyed by independent sorting.
Try changing: Reverse the reference order while leaving voltages fixed.
OCT-09-004
Fit a calibration line to references
A polynomial of degree one gives a gain and an offset from the paired standards. Use the fitted curve beside the observations to inspect the agreement.
Try changing: Change one reference by 0.5 C and inspect the fitted coefficients.
OCT-09-005
Inspect the calibration residuals
Residuals expose deviations that a fitted line can hide at the full measurement scale. Use a zero reference line and keep residuals in the original temperature unit.
source("config/plot-setup.m");voltage=[0.20.40.60.81.0];reference=[5.18.913.017.120.9];p=polyfit(voltage,reference,1);residual=reference-polyval(p,voltage);figure(1);plot(voltage,residual,"o");holdon;plot([0.21.0],[00],"k:");xlabel("Voltage (V)");ylabel("Residual (C)");title("Reference minus fitted calibration");gridon;axispadded;printf("Residual sum of squares: %.6f\n",sum(residual.^2));print(gcf,"figures/OCT-09-005.pdf","-dpdfcairo");closeall;
Try changing: Raise the middle reference by 0.3 C and inspect its residual.
OCT-09-006
Resample a repeatable set of means
Bootstrap resampling draws new samples from these six synthetic observations. Use a fixed seed and state that the displayed percentile interval is an illustrative finite-resampling result.
Try changing: Increase the resample count to 1000 while retaining the seed.
10 · Numerical methods
Choose a numerical method for the mathematical question and state its domain. Compare against an analytic result when one is available, and keep tolerances and brackets explicit.
OCT-10-001
Interpolate between observations
Interpolation supplies values between the four observed times without fitting a global calibration law. Use a named method and keep the measured points visible.
Try changing: Change the upper limit to 6 in both calculations.
OCT-10-004
Locate a threshold crossing
A bracketed root search finds when the decaying response reaches 0.2. Use a bracket that contains the crossing instead of an unexplained initial guess.
Try changing: Move the known minimum to 3.2 and compare the result.
OCT-10-006
Check a differential-equation solution
An adaptive solver evolves a normalized response from its initial value. Use requested output times and an analytic solution to assess the complete trajectory.
Try changing: Change the decay coefficient to 0.8 in the solver and analytic reference.
11 · Files and sampled signals
Read a complete local fixture and preserve its schema when exporting results. For sampled signals, state the sample rate, normalization and treatment of boundaries.
OCT-11-001
Read the local monitoring batch
A numeric CSV reader imports the twelve-row synthetic fixture after its header. Use an explicit skipped-header count and inspect the dimensions before selecting fields.
Try changing: Inspect the voltage column and identify its missing value.
OCT-11-002
Round-trip a native numerical array
Octave’s binary format preserves an array without a text creation-date header. Use a named loaded structure so the restored value cannot silently replace another workspace variable.
Try changing: Save and restore a two-row matrix instead.
OCT-11-003
Export a structured record as JSON
JSON carries the site identifier and its reading array into another tool. Use encode and decode together to check that the exported record retains the expected content.
Try changing: Add a unit field and verify it after decoding.
OCT-11-004
Locate a known frequency with an FFT
A synthetic five-hertz sinusoid supplies an exact frequency reference. Use the stated sample rate and single-sided amplitude normalization to keep the spectrum interpretable.
A three-point convolution averages neighboring observations. Use valid mode to omit edge windows that would otherwise require assumed samples beyond the run.
Try changing: Use a five-point kernel and adjust its center indices.
OCT-11-006
Track cumulative arrivals
A cumulative sum turns completed hourly counts into an intake total. Use counts rather than sampled rates so the accumulation has an unambiguous interpretation.
Try changing: Increase only the third hourly count from 3 to 5.
12 · One field investigation in six steps
Follow the same twelve-row synthetic batch from input inspection to a downloadable summary. Each program starts again from the local CSV so every step remains independently reproducible.
OCT-12-001
Inspect the batch before analysis
The first pass checks the local schema and identifies flagged or nonfinite observations. Use those counts to decide which cleaning rule the next calculation must state.
Try changing: Change one quality flag in a copy of the CSV and rerun this inspection.
OCT-12-002
Apply a visible acceptance rule
A reading is accepted only when its quality flag is one and its voltage is finite. Use the same mask for every retained column to preserve the observation rows.
Try changing: Add an upper accepted voltage limit of 0.85 V.
OCT-12-003
Calibrate the accepted observations
Three exact synthetic standards define the voltage-to-temperature conversion. Use that fit only after rejecting invalid observations, and keep the standards separate from the monitoring batch.
source("config/plot-setup.m");batch=dlmread("data/monitoring.csv",",",1,0);clean=batch(batch(:,4)==1&isfinite(batch(:,3)),:);p=polyfit([00.51],[11121],1);temperature=polyval(p,clean(:,3));figure(1);scatter(clean(:,3),temperature,40,"filled");xlabel("Accepted voltage (V)");ylabel("Calibrated reading (C)");title("Convert the accepted field observations");gridon;axispadded;printf("Gain: %.3f; offset: %.3f; mean: %.3f C\n",p(1),p(2),mean(temperature));print(gcf,"figures/OCT-12-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
Separate standards
Use the three stated reference pairs to fit the calibration.
Try changing: Change the reference offset from 1 C to 2 C in all three standards.
OCT-12-004
Summarize accepted readings by site
Grouping applies the same mean calculation independently to each site. Use site identifiers as the accumulation indices and report how many observations support each mean.
Try changing: Calculate the maximum per site with @max while retaining the counts.
OCT-12-005
Fit a trend within one site
A time trend must refer to a defined site rather than a mixture of site levels. Use the accepted observations from site one and keep its fitted slope in temperature per hour.
source("config/plot-setup.m");batch=dlmread("data/monitoring.csv",",",1,0);selected=batch(:,1)==1&batch(:,4)==1&isfinite(batch(:,3));hours=batch(selected,2);temperature=20.*batch(selected,3)+1;p=polyfit(hours,temperature,1);fine_hours=linspace(min(hours),max(hours),50);figure(1);plot(hours,temperature,"o",fine_hours,polyval(p,fine_hours),"-");xlabel("Time (hours)");ylabel("Site one reading (C)");title("Fit within one collection site");gridon;axispadded;printf("Site one slope: %.6f C/hour; intercept: %.6f C\n",p(1),p(2));print(gcf,"figures/OCT-12-005.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
Site-one mask
Hold the collection site fixed before fitting time.
Slope unit
Report C per hour rather than a unitless coefficient.
Try changing: Select site two and compare its slope and intercept.
OCT-12-006
Export the complete batch summary
A structured summary records the acceptance count and site means alongside the plot. Use the same explicit quality rule for both outputs so the downloaded JSON and figure describe the same observations.
Try changing: Add the rejected count and a unit field to the JSON summary.
13 · Axes, scales and sampling
Control what the viewer can infer from a curve: sampling, gaps, ticks, orientation, logarithmic scales and fixed calendar coordinates. Compare every technique with its gnuplot counterpart.
OCT-13-001
Expose the effect of coarse sampling
A fast oscillation can look like a slow one when too few coordinates are evaluated. Compare two explicit grids over the same time interval before interpreting a sampled curve.
Try changing: Change the coarse grid to 25 coordinates.
OCT-13-002
Break a curve at an excluded interval
A missing interval should remain a gap rather than an invented connecting segment. Assign NaN to the excluded samples while keeping their original coordinates.
source("config/plot-setup.m");hours=0:0.05:6;readings=13+sin(hours);excluded=hours>=2&hours<=3;readings(excluded)=NaN;figure(1);plot(hours,readings,"-");xlabel("Time (hours)");ylabel("Reading (C)");title("Do not join across an unobserved interval");gridon;xlim([06]);ylim([11.514.5]);printf("Excluded coordinates: %d\n",sum(excluded));print(gcf,"figures/OCT-13-002.pdf","-dpdfcairo");closeall;
Try changing: Move the excluded interval to hours 4 through 5.
OCT-13-003
Place named ticks at irregular coordinates
Tick positions and tick labels are independent properties. Name collection visits at their actual unequal time intervals instead of spacing them as categories.
Depth commonly increases downwards even though the numeric values increase. Change the axis direction while retaining the measured depths and temperatures.
source("config/plot-setup.m");depth=[01234];temperature=[1716141211];figure(1);plot(temperature,depth,"o-");set(gca,"ydir","reverse","ytick",0:4);xlabel("Reading (C)");ylabel("Depth below surface (m)");title("Increasing depth runs down the page");gridon;axispadded;print(gcf,"figures/OCT-13-004.pdf","-dpdfcairo");closeall;
Try changing: Use normal direction and compare the reading order.
OCT-13-005
Read a power law on two log axes
A power law becomes a straight line when both coordinates use logarithmic scales. Keep inputs positive and compare a ratio of inputs rather than an additive horizontal step.
source("config/plot-setup.m");interval=logspace(-1,2,101);error_bound=0.02.*interval.^2;figure(1);loglog(interval,error_bound,"-");xlabel("Sampling interval (s)");ylabel("Synthetic error bound (C)");title("A quadratic rule on logarithmic axes");gridon;xlim([0.1100]);ylim([0.00011000]);printf("Doubling the interval multiplies the bound by %.1f\n",...(0.02*2^2)/(0.02*1^2));print(gcf,"figures/OCT-13-005.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
loglog
Make both axes logarithmic without transforming the stored values.
Serial date coordinates preserve elapsed time across a month boundary. Format fixed daily ticks as calendar labels, keeping all dates explicit and independent of the build date.
Try changing: Start on 28 February 2024 to inspect the leap day.
14 · Styles, uncertainty and annotations
Use line handles, quantitative symbol areas, explicit uncertainty bounds and data-derived annotations. Keep units and the definition of uncertainty visible rather than relying on decoration.
OCT-14-001
Style a recorded line through its handle
A graphics handle identifies one series after the line has been created. Use explicit properties when a reusable plotting routine must restyle an existing result.
source("config/plot-setup.m");hours=0:4;readings=[1214131716];figure(1);line_handle=plot(hours,readings);set(line_handle,"linestyle","--","marker","s",..."markerfacecolor",[111],"color",[0.35.60]);xlabel("Time (hours)");ylabel("Reading (C)");title("Restyle one series through its handle");gridon;axispadded;print(gcf,"figures/OCT-14-001.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
line_handle
Retain the object returned by plot.
set (line_handle, ...)
Change the selected series without recreating its data.
Try changing: Change the marker to d and the line style to a solid line.
OCT-14-002
Make bubble area proportional to sample count
The scatter size argument controls marker area in square points. Scale that area directly by a count so a site with twice as many observations receives twice the area.
source("config/plot-setup.m");site=1:4;mean_reading=[12151816];count=[481624];figure(1);scatter(site,mean_reading,12.*count,[0.35.60],"filled");set(gca,"xtick",site);xlim([0.44.6]);ylim([1021]);fork=1:4text(site(k),mean_reading(k)+1,sprintf("n=%d",count(k)),..."horizontalalignment","center");endforxlabel("Site identifier");ylabel("Mean reading (C)");title("Area represents the number of readings");gridon;printf("Largest/smallest marker area: %.1f\n",max(count)/min(count));print(gcf,"figures/OCT-14-002.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
12 .* count
Use 12 square points per observation; do not scale the radius.
Try changing: Double every count and compare both the ratios and absolute marker sizes.
OCT-14-003
Draw an explicit uncertainty envelope
A closed polygon joins lower and upper bounds around a model curve. Use an opaque pale fill for reliable vector export, and state what the supplied bounds represent.
Try changing: Make the tolerance a constant 0.5 C.
OCT-14-004
Keep lower and upper errors distinct
Asymmetric errors describe bounds at different distances from an estimate. Pass the distances separately; the function expects magnitudes rather than the absolute endpoints.
source("config/plot-setup.m");site=1:3;estimate=[121518];lower_distance=[0.51.00.4];upper_distance=[1.20.61.5];figure(1);h=errorbar(site,estimate,lower_distance,upper_distance,"o");set(h,"linestyle","none");set(gca,"xtick",site);xlim([0.53.5]);ylim([1021]);xlabel("Site identifier");ylabel("Reading (C)");title("Supplied lower and upper error distances");gridon;printf("Site two bounds: %.1f to %.1f C\n",...estimate(2)-lower_distance(2),estimate(2)+upper_distance(2));print(gcf,"figures/OCT-14-004.pdf","-dpdfcairo");closeall;
Try changing: Increase only the upper distance at site two to 2 C.
OCT-14-005
Add a threshold in data coordinates
A reference line identifies a fixed limit independently of the observations. Draw it across the chosen time domain and label its unit so its meaning survives a change in data.
source("config/plot-setup.m");hours=0:4;readings=[1214131716];limit=15.5;figure(1);plot(hours,readings,"o-");holdon;plot([04],[limitlimit],"--","color",[.80.30.10]);text(0.15,limit+0.25,sprintf("Limit %.1f C",limit));xlabel("Time (hours)");ylabel("Reading (C)");title("Compare observations with a fixed limit");gridon;xlim([-0.24.2]);ylim([1118]);printf("Above limit: %d of %d\n",sum(readings>limit),numel(readings));print(gcf,"figures/OCT-14-005.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
[limit limit]
Use equal endpoint heights for a horizontal reference.
Try changing: Lower the limit to 13.5 C and predict the count.
OCT-14-006
Derive an extreme label from the data
The index returned by max locates the observation as well as its value. Build both the marker position and label from that index so they move together when the readings change.
source("config/plot-setup.m");hours=[01246];readings=[1214131716];[peak,index]=max(readings);figure(1);plot(hours,readings,"o-");holdon;plot(hours(index),peak,"s","color",[.80.30.10],"markersize",8);text(hours(index),peak+0.6,sprintf("Maximum %.1f C",peak),..."horizontalalignment","center");xlabel("Time (hours)");ylabel("Reading (C)");title("One computed index controls the annotation");gridon;xlim([-0.56.5]);ylim([1119]);printf("Maximum: %.1f C at hour %.1f\n",peak,hours(index));print(gcf,"figures/OCT-14-006.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
[peak, index] = max (...)
Return the maximum and its first position.
hours(index)
Use the actual time coordinate rather than the row number.
Try changing: Raise the second reading to 18 C and observe the moving label.
15 · Bars, paired comparisons and totals
Choose a chart that matches a categorical comparison: adjacent series, contributions, percentages, ranked sites, paired changes or a running balance. Compute the relevant quantities before drawing them.
OCT-15-001
Compare two batches with grouped bars
Grouped bars place two measurements beside each site without adding them. Use a matrix with sites in rows and batches in columns, and label the series explicitly.
source("config/plot-setup.m");values=[1214;1516;1817];figure(1);bar(1:3,values,"grouped");set(gca,"xtick",1:3,"xticklabel",{"North","East","South"});xlabel("Monitoring site");ylabel("Mean reading (C)");title("Compare batches within each site");ylim([021]);gridon;key=legend("Batch A","Batch B","location","northwest");set(key,"fontsize",11,"box","off");print(gcf,"figures/OCT-15-001.pdf","-dpdfcairo");closeall;
Try changing: Add four rejected observations at site two.
OCT-15-003
Normalize every stack to a percentage
Normalizing rows separates composition from sample size. Divide each status count by its own site total before plotting, and keep the raw counts available for interpretation.
Try changing: Double both counts at site one and check that its percentages stay fixed.
OCT-15-004
Rank sites with horizontal bars
Horizontal bars leave room for site names and make ordered comparisons easy to scan. Sort values and their labels with the same permutation before reversing the categorical axis.
Try changing: Change East valley to 25 observations and inspect its new rank.
OCT-15-005
Connect before and after measurements
A dumbbell chart emphasizes paired change within each site. A horizontal connector shows the interval; marker shape and color identify the two endpoints.
A running balance determines both ends of each floating bar. Compute the lower and upper endpoints with min and max so decreases and negative totals remain correct.
Try changing: Change Lost to -15 and check the final negative balance.
16 · Distributions and empirical probabilities
Distinguish counts, probability density, cumulative probability and strict exceedance. Build the summaries from explicit samples with core Octave functions, including a small kernel-density violin.
OCT-16-001
Count observations with explicit bin edges
Bin boundaries determine which observations are counted together. Use histc to expose the left-closed, right-open rule, and check the separate count for the final edge.
Try changing: Shift the internal edges by 0.5 C and inspect the counts.
OCT-16-002
Normalize unequal bins by their widths
Probability density is a count divided by sample size and bin width. Unequal bins make the distinction visible: area represents probability while height is probability per degree.
source("config/plot-setup.m");readings=[10111112121213141517];edges=[10121518];count=histc(readings,edges);widths=diff(edges);assert(count(end)==0);density=count(1:end-1)./(numel(readings).*widths);figure(1);holdon;fork=1:numel(widths)fill([edges(k)edges(k+1)edges(k+1)edges(k)],...[00density(k)density(k)],[0.35.60],"edgecolor",[111]);endforxlabel("Reading (C)");ylabel("Probability density (1/C)");title("Probability is rectangle area");xlim([919]);ylim([0.22]);printf("Total histogram area: %.6f\n",sum(density.*widths));print(gcf,"figures/OCT-16-002.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
diff (edges)
Compute each bin width in C.
count / (sample size * width)
Normalize the density so its integrated area is one.
Try changing: Move the middle edge from 15 to 16 C and recheck the total area.
OCT-16-003
Keep tied observations in a right-continuous ECDF
An empirical cumulative distribution gives the fraction at or below each value. Aggregate tied readings before drawing the step so the entire jump occurs at their shared coordinate.
source("config/plot-setup.m");readings=[10111112121213141517];[value,~,group]=unique(readings(:));count=accumarray(group,1);fraction=cumsum(count)/numel(readings);figure(1);stairs([9;value;18],[0;fraction;1],"-");xlabel("Reading threshold (C)");ylabel("Fraction at or below threshold");title("Ties make one larger cumulative jump");gridon;xlim([918]);ylim([-.041.04]);printf("Fraction at or below 12 C: %.3f\n",fraction(value==12));print(gcf,"figures/OCT-16-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
unique / accumarray
Count all equal observations together.
stairs
Retain each cumulative level until the next observed value.
Try changing: Replace one 12 C reading with 11 C and inspect both jumps.
OCT-16-004
Accumulate weighted empirical probabilities
Observation weights change the probability mass contributed by each reading. Sum weights within tied values and divide by total weight, rather than dividing by the number of rows.
Try changing: Set all weights to one and compare with the unweighted ECDF.
OCT-16-005
Plot strict exceedance above a threshold
Subtracting the right-continuous ECDF from one gives the fraction strictly above the threshold. Equal readings belong to the excluded side of a strict comparison, which matters at ties.
Try changing: Compare the fractions strictly above 11.9 C and 12 C.
OCT-16-006
Mirror a kernel density into a violin
A violin traces a density estimated from the actual observations. Write the Gaussian-kernel calculation explicitly so the bandwidth and the conversion from density to width remain visible without an add-on package.
source("config/plot-setup.m");readings=[101111.51212.212.6131515.516];y=linspace(8,18,201).';bandwidth=0.6;z=(y-readings)/bandwidth;density=mean(exp(-0.5.*z.^2),2)/(bandwidth*sqrt(2*pi));width=0.8.*density;figure(1);fill([1-width;flipud(1+width)],[y;flipud(y)],...[.70.83.92],"edgecolor",[0.35.60]);holdon;plot(ones(size(readings)),readings,"k.","markersize",8);set(gca,"xtick",1,"xticklabel",{"Site one"});ylabel("Reading (C)");title("Density width depends on a stated bandwidth");xlim([.51.5]);ylim([818]);printf("Density area over shown range: %.6f\n",trapz(y,density));print(gcf,"figures/OCT-16-006.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
bandwidth = 0.6
Set the Gaussian smoothing width in C.
0.8 .* density
Use one explicit density-to-width multiplier; points show the raw sample.
Try changing: Halve the bandwidth and inspect the extra density peaks.
17 · Scatter density and multivariate structure
Reveal overlap, encode an additional measurement and summarize joint structure. Compute density, principal components and spread from the supplied arrays instead of plotting prepared statistical results.
OCT-17-001
Separate coincident observations with fixed jitter
Overlapping markers can hide repeated values within a site. Add a small reproducible horizontal displacement while preserving the measured temperatures exactly.
Try changing: Reduce the jitter amplitude from 0.12 to 0.04.
OCT-17-002
Encode a third measurement with point color
A scatter color argument can carry one additional numeric variable. Fix its range and label the colorbar so the same hue has the same meaning across a comparison.
Try changing: Replace one battery value with 55 and inspect its color.
OCT-17-003
Count scattered observations into rectangular cells
A two-dimensional count grid reveals where observations accumulate. Map each coordinate to a bin and accumulate row/column pairs, checking that no point falls outside the declared domain.
source("config/plot-setup.m");rng(17,"twister");x=randn(400,1);y=0.6.*x+0.5.*randn(400,1);edges=-4:0.5:4;centers=(edges(1:end-1)+edges(2:end))/2;[~,ix]=histc(x,edges);[~,iy]=histc(y,edges);assert(all(ix>0&ix<numel(edges)&iy>0&iy<numel(edges)));count=accumarray([iyix],1,[1616]);figure(1);imagesc(centers,centers,count);set(gca,"ydir","normal");colormap(viridis(64));cb=colorbar();ylabel(cb,"Observations per cell");xlabel("Sensor A residual (C)");ylabel("Sensor B residual (C)");title("Rectangular bins summarize local density");axisimage;printf("Counted observations: %d\n",sum(count(:)));print(gcf,"figures/OCT-17-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
accumarray ([iy ix], 1, ...)
Use y bins as matrix rows and x bins as columns.
Domain assertion
Reject out-of-range points rather than silently losing observations.
Try changing: Use unit-wide bins and adjust the matrix size to 8 by 8.
OCT-17-004
Compute principal-component scores from the sample
Singular-value decomposition of centered measurements gives principal directions and scores. Resolve each direction sign explicitly so equivalent SVD sign choices cannot flip the displayed axes.
Try changing: Increase the second measurement in row three and compare the variance share.
OCT-17-005
Draw an ellipse from the sample covariance
The eigenvectors and eigenvalues of a covariance matrix determine the axes of a spread ellipse. State its scale as two sample standard deviations along each principal direction; it is not automatically a confidence region.
Try changing: Change the multiplier from 2 to 1 and inspect the same sample.
OCT-17-006
Compare measurements on parallel normalized axes
Parallel coordinates place each measurement on a separate vertical axis. Normalize against explicit domain limits rather than the current sample extrema so adding a site does not redefine the scales.
Try changing: Change the count domain from 0-20 to 0-30.
18 · Color scales and matrix heatmaps
Treat color as a quantitative scale with a defined range, midpoint and unit. Keep cell positions, missing values and color transforms explicit so matrix views can be compared honestly.
OCT-18-001
Center a diverging color scale on zero
Signed residuals need a neutral midpoint that stays at zero. Interpolate a blue-white-orange palette and choose symmetric color limits even when the observed extrema are unequal.
Try changing: Change the largest positive residual to 1 without changing the color limits.
OCT-18-002
Share one color range across two panels
Separate autoscaling can make unequal fields look deceptively alike. Give both axes the same explicit color limits and attach a colorbar to each to expose the shared mapping.
Try changing: Replace the second matrix with first+1 and keep both color ranges fixed.
OCT-18-003
Print each heatmap value at its cell center
Numeric annotations make a small heatmap readable without estimating every hue. Position text in matrix coordinates and choose a readable text color against the cell fill.
source("config/plot-setup.m");readings=[101215;111417;131618];figure(1);imagesc(readings);colormap(viridis(64));caxis([1018]);forrow=1:3forcolumn=1:3ink=[000];ifreadings(row,column)<14;ink=[111];endiftext(column,row,sprintf("%g",readings(row,column)),..."horizontalalignment","center","color",ink);endforendforset(gca,"xtick",1:3,"ytick",1:3);axisimage;xlabel("Visit");ylabel("Site");title("Cell centers retain the actual readings");cb=colorbar();ylabel(cb,"Reading (C)");print(gcf,"figures/OCT-18-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
text (column, row, ...)
Put annotations at the corresponding image cell centers.
Text contrast rule
Use white on the darker low-value cells and black on brighter cells.
Try changing: Add 0.5 C to every reading and print one decimal place.
OCT-18-004
Keep missing cells visibly separate from low values
Missing data has no numeric position on the color scale. Keep the missing-value mask, use a finite rendering array, and draw the masked cell explicitly as a white region labeled NA.
source("config/plot-setup.m");readings=[101215;11NaN17;131618];missing=isnan(readings);shown=readings;shown(missing)=10;figure(1);imagesc(shown);colormap(viridis(64));caxis([1018]);holdon;[row,column]=find(missing);fork=1:numel(row)fill(column(k)+[-.5.5.5-.5],row(k)+[-.5-.5.5.5],...[111],"edgecolor",[.6.6.6]);text(column(k),row(k),"NA","horizontalalignment","center");endforset(gca,"xtick",1:3,"ytick",1:3);axisimage;xlabel("Visit");ylabel("Site");title("White NA cells are outside the numeric scale");cb=colorbar();ylabel(cb,"Reading (C)");printf("Missing cells: %d\n",sum(missing(:)));print(gcf,"figures/OCT-18-004.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
missing = isnan (readings)
Retain missingness separately from the finite rendering values.
White cell polygon + NA
Mark missing cells with native graphics, independently of the numeric palette.
Try changing: Make the upper-right cell NaN as well.
OCT-18-005
Map orders of magnitude through log color
A linear color scale can hide low values when magnitudes span several powers of ten. Transform positive values with log10 and label the colorbar ticks in the original count unit.
Try changing: Multiply every count by two and expand the stated color range if needed.
OCT-18-006
Quantize a field into stated color bands
A short colormap groups a continuous field into a few explicit intervals. Keep the range and colorbar boundaries visible so the bands are understood as bins rather than abrupt physical changes.
Try changing: Use eight colors and colorbar ticks every 0.125.
19 · Geometry, contours and spatial curves
Preserve geometric meaning with equal units, explicit contour levels and fixed 3D views. Compare polar curves, wireframes, trajectories and offset signal slices without changing the common export setup.
OCT-19-001
Give equal distances equal physical lengths
A parametric inspection path should not change shape because of axis stretching. Apply equal data units so a one-meter displacement occupies the same length in both directions.
Try changing: Use a north radius of two meters and confirm a circular path.
OCT-19-002
Plot a directional response in polar coordinates
A polar plot treats the first coordinate as an angle in radians and the second as radial response. Keep all radii positive so the direction is not silently reversed by a negative value.
source("config/plot-setup.m");angle=linspace(0,2*pi,181);response=1+0.3.*cos(2.*angle);figure(1);polar(angle,response,"-");title("Directional response; angle in degrees, radius in relative units");printf("Radial range: %.2f to %.2f\n",min(response),max(response));print(gcf,"figures/OCT-19-002.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
polar (angle, response)
Supply angles in radians; the native grid labels degrees.
1 + 0.3*cos(2*angle)
Keep the directional response between 0.7 and 1.3.
Try changing: Change the harmonic from two lobes to three.
OCT-19-003
Inspect a sampled field as a wireframe
A wireframe exposes the sampling grid without filling every cell. Use a fixed camera to compare this geometry with a filled surface or a later change in grid resolution.
Try changing: Reduce the grid to nine samples along each dimension.
OCT-19-004
Choose only meaningful contour levels
Explicit contour levels answer threshold questions without adding arbitrary intermediate lines. Repeat a single level twice when only one isoline is needed, or supply a complete increasing level vector.
Try changing: Request only the 0.5 isoline with the level vector [0.5 0.5].
OCT-19-005
Trace a continuous route through three dimensions
A three-dimensional line preserves the sequence of positions along a route. Fix the viewing direction and equal spatial units before interpreting the apparent curvature or vertical spacing.
source("config/plot-setup.m");angle=linspace(0,4*pi,241);east=cos(angle);north=sin(angle);height=angle/(2*pi);figure(1);plot3(east,north,height,"-");view(45,25);axisequal;gridon;xlim([-1.31.3]);ylim([-1.31.3]);zlim([-.22.2]);xlabel("East offset (m)");ylabel("North offset (m)");zlabel("Height (m)");title("A fixed route ascends one meter per turn");printf("Turns: %.1f; final height: %.1f m\n",angle(end)/(2*pi),height(end));print(gcf,"figures/OCT-19-005.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
plot3 (east, north, height)
Join ordered positions in three spatial dimensions.
Try changing: Double the vertical ascent per turn.
OCT-19-006
Separate repeated signals as a spatial waterfall
A native waterfall draws one vertical slice per collection visit. Keep a common amplitude scale and explicit visit coordinates so offsets do not masquerade as changes in signal strength.
source("config/plot-setup.m");time=linspace(0,6,61);visit=1:4;[t,v]=meshgrid(time,visit);response=exp(-0.5.*(t-(1+0.7.*v)).^2);figure(1);waterfall(t,v,response);view(45,30);colormap(viridis(64));xlabel("Time within run (s)");ylabel("Collection visit");zlabel("Response");title("Repeated responses share one amplitude scale");xlim([06]);ylim([.54.5]);zlim([01.1]);print(gcf,"figures/OCT-19-006.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
waterfall (t, v, response)
Draw one native slice for each matrix row.
meshgrid (time, visit)
Retain the actual time and collection-visit coordinates.
Try changing: Move the response centers later by changing the visit multiplier from 0.7 to 1.0.
20 · Layouts and model diagnostics
Use layout to support an analytical comparison: a local zoom, a second unit, linked residuals, competing interpolants, derivative step sizes and a fitted nonlinear response. Every result is computed from the shown inputs.
OCT-20-001
Place a local zoom inside the main axes
A manually positioned axes object can show a short interval beside the full response. Choose the inset position in normalized figure coordinates and label its narrower domain explicitly.
source("config/plot-setup.m");time=linspace(0,6,301);response=exp(-(time-3).^2);figure(1);main_axes=axes("position",[.13.16.76.72]);plot(main_axes,time,response,"-");gridon;xlabel(main_axes,"Time (s)");ylabel(main_axes,"Response");title(main_axes,"A local zoom retains the full response context");xlim(main_axes,[06]);ylim(main_axes,[-.051.1]);inset=axes("position",[.66.55.21.24],"fontsize",8);plot(inset,time,response,"-");xlim(inset,[2.73.3]);ylim(inset,[.91.01]);set(inset,"xtick",[2.733.3],"ytick",[.91]);title(inset,"Peak zoom");print(gcf,"figures/OCT-20-001.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
axes (position, [left bottom width height])
Place each axes in fractions of the figure size.
Explicit axes handles
Apply zoom limits to the inset without changing the main view.
Try changing: Move the inset to the lower-right corner and check that it covers no important data.
OCT-20-002
Label two independent quantities on separate axes
Temperature and battery charge have different units and independent scales. plotyy returns both axes so each can be labeled and constrained explicitly; visual line crossings have no shared numeric meaning.
source("config/plot-setup.m");hours=0:4;temperature=[1214131716];charge=[9588796960];figure(1);[ax,h1,h2]=plotyy(hours,temperature,hours,charge);set(h1,"marker","o","color",[0.35.60]);set(h2,"marker","s","color",[.80.30.10]);set(ax(1),"ycolor",[0.35.60]);set(ax(2),"ycolor",[.80.30.10]);xlim(ax(1),[-.24.2]);xlim(ax(2),[-.24.2]);ylim(ax(1),[1020]);ylim(ax(2),[50100]);xlabel(ax(1),"Time (hours)");ylabel(ax(1),"Reading (C)");ylabel(ax(2),"Battery charge (%)");title(ax(1),"Each series keeps its own unit");print(gcf,"figures/OCT-20-002.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
[ax, h1, h2] = plotyy (...)
Return two axes and their independently styled lines.
Try changing: Change only the battery-axis lower bound to zero and inspect the apparent slopes.
OCT-20-003
Link a fitted curve to its residual panel
A residual panel complements the fitted response while retaining the same time coordinate. Link only the horizontal limits so zooming one panel keeps observations aligned without merging their different vertical units.
source("config/plot-setup.m");hours=0:4;readings=[1214131716];p=polyfit(hours,readings,1);fitted=polyval(p,hours);figure(1);top=subplot(2,1,1);plot(hours,readings,"o",hours,fitted,"-");ylabel("Reading (C)");title("A fitted trend and its aligned residuals");gridon;bottom=subplot(2,1,2);stem(hours,readings-fitted,"filled");xlabel("Time (hours)");ylabel("Residual (C)");gridon;linkaxes([topbottom],"x");xlim(top,[-.24.2]);ylim(top,[1118]);ylim(bottom,[-22]);printf("Residual sum of squares: %.6f\n",sum((readings-fitted).^2));print(gcf,"figures/OCT-20-003.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
linkaxes ([top bottom], x)
Synchronize horizontal limits across both axes.
readings - fitted
Show signed discrepancies below the fitted response.
Try changing: Zoom the top axes to hours 1 through 3.
OCT-20-004
Compare linear and shape-preserving interpolation
Interpolation choices imply different behavior between the same observed coordinates. Compare linear, PCHIP and cubic spline curves over the measured domain, keeping the original sample markers visible.
source("config/plot-setup.m");time=0:5;response=[0.1.12.9.921];fine=linspace(0,5,301);linear=interp1(time,response,fine,"linear");pchip_value=interp1(time,response,fine,"pchip");spline_value=interp1(time,response,fine,"spline");figure(1);h=plot(fine,linear,"-",fine,pchip_value,"--",fine,spline_value,":");holdon;plot(time,response,"ko");key=legend(h,{"Linear","PCHIP","Spline"},"location","northwest");set(key,"fontsize",11,"box","off");xlabel("Time (hours)");ylabel("Normalized response");title("Interpolation behavior depends on the method");gridon;xlim([-.25.2]);ylim([-.11.1]);printf("PCHIP range: %.6f to %.6f\n",min(pchip_value),max(pchip_value));printf("Spline range: %.6f to %.6f\n",min(spline_value),max(spline_value));print(gcf,"figures/OCT-20-004.pdf","-dpdfcairo");closeall;
Parameter
Meaning in this example
interp1 (..., pchip)
Use a piecewise cubic method that preserves monotonicity here.
spline
Compare a cubic spline through exactly the same observations.
Try changing: Replace the rapid rise at hour 3 with a gradual rise and compare the methods.
OCT-20-005
Balance truncation and roundoff in a derivative
A centered finite difference approaches an analytic derivative as the step shrinks, until cancellation limits the result. Plot absolute error against step size rather than assuming the smallest step is always best.
Try changing: Extend the step range down to 1e-12.
OCT-20-006
Fit a positive nonlinear decay model
A nonlinear objective can estimate amplitude and decay rate together. Optimize their logarithms so both parameters remain positive, and check convergence before presenting the resulting curve.
The new graphical chapters follow questions also explored in the gnuplot tour.
Each of their 48 examples has its own direct comparison link. The Octave programs
compute their arrays explicitly and render through the same pinned native toolkit;
the examples and prose are original rather than translations of gnuplot scripts.
Rectangular count bins in OCT-17-003 illustrate the density question of the
gnuplot hexbin chapter, with different cell geometry. The covariance ellipse
shows sample spread rather than a confidence region. Kernel density and PCA
are computed with core functions; no statistics package is installed by the build.
Choosing a method
Start with the question, the data shape and the unit of the result. A matrix
transformation, independent array arithmetic and a statistical summary are different
operations even when they use the same numbers. Check orientation before a reduction
and inspect quality flags before fitting a model.
Keep a supplied array distinct from a sampled physical process. State the sample
rate for a spectrum, the error-bar definition for a summary and the time domain
for a solver. These examples use synthetic data; their fitted relationships are
features of that constructed batch rather than evidence about a real environment.
References
The prose, synthetic inputs and programs are original. Syntax was checked with
the installed 11.3.0 command help and the actual executions. The examples use only
core functions; no build invokes pkg install or downloads external datasets.
Original content is dedicated under CC0 1.0. Tour arrangement and the publishing
framework are CC BY 4.0 by Lukas C. Bossert. See license notes,
CC0, CC BY and the font’s SIL Open Font License.
GNU Octave and the separately installed rendering tools retain their own licenses.