Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

For data scientists, biologists, engineers and traders

Charts for data scientists

ROC curves with the AUC in the legend, a precision-recall curve, a normalized confusion matrix, a regression line with its 95 % confidence band and R², 2D density contours of 20 000 points and a dendrogram of hierarchical clustering.

Charts for data scientists
#![allow(unused)]
fn main() {
ax.roc_curve("gradient boosting", &labels, &scores);
ax.pr_curve("gradient boosting", &labels, &scores);
ax.confusion_matrix(["cat", "dog", "bird"], &actual, &predicted, true);
ax.regplot(&x, &y);
ax.density_contour(&a, &b);
ax.dendrogram(names, &features);
}

Model evaluation and explanation

A SHAP summary (beeswarm) of a credit-default model, calibration curves of a well calibrated and an over-confident model (Brier scores in the legend), a learning curve with ±1σ bands, a cumulative gain chart, a raincloud plot (half violin, box and points) and an UpSet plot of genes found by four assays.

SHAP summary, calibration, learning curve, gain, raincloud, UpSet
#![allow(unused)]
fn main() {
ax.shap_summary(&feature_names, &shap_values, &feature_values, 10);
ax.calibration_curve("logistic", &labels, &probabilities, 10);
ax.learning_curve(&sizes, &train_scores, &validation_scores);
ax.gain_curve("logistic", &labels, &scores);      // also lift_curve
ax.raincloud([("eu-west", a), ("us-east", b)]);
ax.upset(&[("RNA-seq", genes_a), ("ATAC-seq", genes_b)], 12);
}

Code of this example · cargo run --release -p plot-data-science


Charts for biology, genomics and medicine

A DNA sequence logo (letters scaled to their information content), a gene track (exons, introns, strand), a GWAS Manhattan plot with its p-value Q-Q plot, a volcano plot naming the top genes, single-cell clusters on a UMAP, a dose-response curve with a four-parameter logistic fit and IC50, Kaplan-Meier survival with the log-rank test, a forest plot of hazard ratios, and a clustermap of gene expression.

Biology, genomics and medicine Clustermap Circos, Hi-C, coverage, phylogenetic trees, oncoprint, mutation lollipop

Genomics: a Circos plot (hg38 chromosomes, copy number, translocations), a Hi-C contact map with TADs, exome coverage with a minimum-depth check, phylogenetic trees from Newick text (rectangular and circular), an oncoprint of ten cancer genes and TP53 mutations along the protein.

#![allow(unused)]
fn main() {
ax.circos(&chromosomes).track(&chrom, &pos, &copy_number).links(&translocations);
ax.hic(matrix, 1.0, 0.025).domains(&tads);
ax.coverage(&pos, &depth).min_depth(20.0);
ax.phylo_tree(newick);              // phylo_tree_circular(newick)
ax.oncoprint(&genes, samples, &events);
ax.mutation_lollipop(393.0, &domains, &mutations);
}
#![allow(unused)]
fn main() {
ax.sequence_logo(&aligned);
ax.gene_track(&genes);
ax.manhattan(chromosome, position, &p);
ax.volcano(names, &log2_fc, &p, 1.0, 1e-3, 6);
ax.embedding(&umap_x, &umap_y, cell_types);
ax.dose_response(&dose, &response);
ax.kaplan_meier([("standard", t1, e1), ("new treatment", t2, e2)]);
ax.forest_plot(studies, hr, low, high, 1.0).summary_last(true);
fig.clustermap(genes, samples, &expression);
}

Code of this example · cargo run --release -p plot-biology


3D biology: DNA, molecules, cells

A DNA double helix with base pairs colored by base and a marked TATA box, real structures from the Protein Data Bank (the B-DNA dodecamer 1BNA as ball-and-stick with CPK colors, the protein crambin 1CRN as a backbone tube colored from N- to C-terminus), a cell (translucent membrane, nucleus with nucleolus, mitochondria, vesicles, ribosomes), an organoid of cells colored by a marker gene, and single-cell clusters on a 3D UMAP.

DNA and a cell turning around the z, x and y axes DNA helix, PDB structures, cell, organoid, 3D UMAP Protein cartoons, Ramachandran plot, isosurfaces

Proteins: ubiquitin (PDB 1UBQ) and crambin (1CRN) as cartoons (helices as ribbons, strands as arrows, from the PDB HELIX/SHEET records), ubiquitin colored from N- to C-terminus, its Ramachandran plot from the backbone dihedrals, and isosurfaces (marching tetrahedra) of a density around crambin and of a nucleus with its nucleolus.

#![allow(unused)]
fn main() {
ax.molecule(Molecule::from_pdb(&pdb)).style(MolStyle::Cartoon);
let angles = molecule.phi_psi();               // (φ, ψ, residue)
ax.ramachandran(&phi, &psi);
ax.isosurface_fn(|x, y, z| density(x, y, z), bounds, 64, 0.55);
ax.isosurface(&volume, [nx, ny, nz], bounds, level);   // microscopy / CT stacks
}
#![allow(unused)]
fn main() {
ax.dna_helix("ATGCGTATAAAAGCC").highlight(5..11, "#ffd400", Some("TATA box"));
ax.molecule(Molecule::from_pdb(&pdb)).style(MolStyle::BallAndStick);
ax.molecule(Molecule::from_pdb(&pdb)).style(MolStyle::Backbone).coloring(MolColor::Rainbow);
ax.ellipsoid([0.0, 0.0, 0.0], [10.0, 8.0, 6.0]).opacity(0.16);   // membrane
ax.spheres3d(&x, &y, &z, [1.0]).values(&expression, Colormap::Viridis);
ax.embedding3d(&umap1, &umap2, &umap3, cell_types);
ax.rotate(Axis3::X, 30.0);
}

Molecules are read from PDB (ATOM/HETATM) or XYZ text; bonds are found from covalent radii with a spatial grid (linear time). Styles: ball-and-stick, sticks, space-filling and backbone; colors by element, chain or along the chain. Structures open with their longest extent across the screen (principal axes) and far parts fade into the background for depth.

Turning the scenes

cargo run --release -- --window opens the figure in a window: drag to turn, wheel to zoom, X/Y/Z to rotate by 15° around that axis (Shift+key the other way), R to reset, hover an atom or base pair for its name. In code: ax.rotate(Axis3::Z, 15.0), ax.roll(..), ax.camera(azimuth, elevation); rotate.gif is recorded that way.

Code of this example · cargo run --release -p plot-biology-3d


Charts for engineers

An FFT amplitude spectrum, the spectrogram of a chirp with a steady tone, the Nyquist plot of a second-order system, impedances on a Smith chart, and a Bode plot (magnitude and unwrapped phase) of two transfer functions.

Charts for engineers Charts for engineers Streamlines, ternary, 3D waterfall, SPC chart, Pareto, 3D vectors, 3D bars

Streamlines of a flow around a cylinder and of a dipole field (colored by speed, log scale when it spans decades), a ternary diagram of soil texture, a 3D waterfall of vibration spectra, an SPC control chart (±1/2/3σ zones, Western Electric rules 1 and 2), a Pareto chart, 3D vectors of the field around a wire and 3D bars.

#![allow(unused)]
fn main() {
ax.streamplot(|x, y| (u(x, y), v(x, y)), (-3.0, 3.0), (-2.0, 2.0), 28);
ax.ternary(&sand, &silt, &clay).names("sand %", "silt %", "clay %");
ax.waterfall3d(&freq, &time, spectra);
ax.control_chart(&diameters);
ax.pareto(causes, counts);
ax.quiver3d(points, vectors);
ax.bar3d(months, sites, energy);
}
#![allow(unused)]
fn main() {
ax.spectrum(&signal, fs);
ax.spectrogram(&signal, fs, 512, 64);
let w = logspace(0.01, 100.0, 400);
let h = freq_response(&[1.0], &[1.0, 0.4, 1.0], &w);   // 1 / (s² + 0.4s + 1)
ax.nyquist(&h);
ax.smith(&impedances);
fig.bode("1/(s²+0.4s+1)", &w, &h);
}

Code of this example · cargo run --release -p plot-engineering


Charts for traders

Candlesticks on a trading-day axis (no weekend gaps) with the Ichimoku cloud and VWAP, a volume profile on the same price axis (point of control and value area), stochastic, ATR, order book depth, drawdown of an equity curve and a Renko chart. Linked crosshair and zoom work across the panels in a window.

Charts for traders Liquidity heatmap, footprint, market profile, option payoffs, volatility surface

Order flow and options: an order-book liquidity heatmap with the traded price, footprint bars (bid × ask per price level, imbalances, point of control), a market profile (TPO letters, POC, value area), the payoff of an iron condor and a covered call at expiry and before it (Black–Scholes), and an implied volatility surface.

#![allow(unused)]
fn main() {
ax.liquidity_heatmap((t0, t1), (p0, p1), &depth);
ax.footprint(bars, 0.25);
ax.market_profile(&half_hour_ranges, 1.0);
ax.option_payoff(&[OptionLeg::Put { strike: 95.0, premium: 2.0, qty: -1.0 }, /* … */], (82.0, 118.0), 30.0, 0.22, 0.03);
ax.volatility_surface(&strikes, &maturities, &iv);
}
#![allow(unused)]
fn main() {
let x = ax.trading_axis(&times, "%d %b");
ax.candlestick(&x, &open, &high, &low, &close);
ax.ichimoku(&x, &high, &low, &close);
ax.vwap(&x, &high, &low, &close, &volume);
profile.volume_profile(&close, &volume, 24);
osc.stochastic(&x, &high, &low, &close, 14, 3);
book.depth_chart(&bids, &asks);
dd.drawdown(&x, &equity);
renko.renko(&close, 2.0);
}

Code of this example · cargo run --release -p plot-trading


Drawing tools

The drawing tools of trading platforms, in code or with the mouse:

  • trend lines and rays (continued to the edge of the plot);
  • price levels, with the value in a tag on the price axis;
  • Fibonacci retracements: the 0, 23.6, 38.2, 50, 61.8, 78.6 and 100 % levels, with their prices, over shaded bands.

Drawings keep their data positions when you zoom or pan, and they are saved with the chart (PNG, SVG, PDF, HTML).

Candlesticks with a support ray, a trend line, a resistance level and a Fibonacci retracement
#![allow(unused)]
fn main() {
ax.candlestick(x, open, high, low, close);
ax.ray((5.0, 98.3), (101.0, 123.9)).label("support line");
ax.price_level(152.1).label("resistance");
ax.fib_retracement((0.0, 98.3), (53.0, 152.1));
}

In a window (cargo run --release -- --show), you draw with the mouse:

KeyThen
Tdrag from one point to another: trend line
Lclick at a price: price level
Fdrag from the start of a move to its end: Fibonacci retracement
Backspacetakes back the last drawing

A dashed preview follows the mouse while you drag. The same drawings are available in the JSON spec ("drawings": [{"type": "fib", "from": [x, y], "to": [x, y]}, …]) and in Python (ax.trendline, ax.price_level, ax.fib_retracement).

Code of this example · cargo run --release -p plot-drawing-tools


Volume files: NIfTI, DICOM, VTK, MetaImage

A head phantom (the 3D Shepp–Logan ellipsoids, in Hounsfield-like units, with one octant cut away) is written as a NIfTI file and as a DICOM series of 96 slices, read back with VolumeData::read and rendered.

Bone with and without gradient lighting from NIfTI, soft tissue from a DICOM series
  • Lighting: the left and middle images differ only in lighting. The value gradient gives every surface in the volume diffuse light and a highlight, so the cut-away shows its shape. Lighting is on by default; .shading(false) turns it off.
  • Physical units: voxel spacing (1.5 mm in plane, 2 mm between slices) and the origin come from the files, so the volume keeps its proportions.
  • Speed: both files (128 × 128 × 96 voxels) are read in about 4 ms each; the three renderings are saved in about 115 ms.
#![allow(unused)]
fn main() {
use dataviz::plot::volume_file::VolumeData;

let scan = VolumeData::read("head.nii.gz")?;     // .nii .nii.gz .vtk .mhd .mha .dcm, or a DICOM directory
ax.volume_data(&scan)
    .range(-1000.0, 1000.0)                       // bone window (HU)
    .threshold(0.6)
    .colormap(Colormap::Magma);
}
FormatRead
NIfTI-1 and NIfTI-2 (.nii, .nii.gz)any data type, either byte order, intensity scaling; for 4D files the first volume
DICOM (a directory of slices, or a multi-frame .dcm)sorted along the slice normal, rescale slope and intercept applied; uncompressed transfer syntaxes
VTK legacy structured points (.vtk)ASCII or binary, the first scalar array
MetaImage (.mhd + raw, .mha)plain or zlib-compressed

In Python: ax.volume("head.nii.gz"). In a JSON spec: {"type": "volume", "path": "scans/ct/"}.

Code of this example · cargo run --release -p plot-volume-files


Business and editorial charts

A bullet chart of KPIs against targets, a dumbbell chart, a slope chart, a bump chart of league positions, a waffle chart, a marimekko (mosaic) chart, a chord diagram of migration flows, a streamgraph and a horizon chart of six stocks.

Bullet, dumbbell, slope, bump, waffle, marimekko, chord, streamgraph, horizon
#![allow(unused)]
fn main() {
ax.bullet(kpis, values, targets, &ranges);
ax.dumbbell(countries, &y2000, &y2023).labels("2000", "2023");
ax.slope(brands, &share_2020, &share_2025, "2020", "2025");
ax.bump(teams, seasons, &ranks);
ax.waffle(sources, shares);
ax.marimekko(regions, segments, &sales);
ax.chord(regions, &flows);
ax.streamgraph(&weeks, &[("Pop", pop), ("Rock", rock)]);
ax.horizon(&days, &[("AAA", returns_a), ("BBB", returns_b)]);
}

Shapes of one color are merged into one path and curves are flattened, so each chart is a handful of nodes for the rasterizer.

Code of this example · cargo run --release -p plot-business