Plotting in Rust with plotters

Day 4, lecture 2

Rust for bioinformaticians

What this lecture is

  • One picture per analysis — emitted by the analysis itself
  • plotters as a Rust answer to matplotlib and ggplot2
  • The mental model: drawing area, chart context, series
  • Histograms, scatter plots, line plots, multiple series
  • Where plotters is great, and where it is not

Why plot from Rust?

  • The same binary that does the analysis emits the figure
  • No “now open a notebook and plt.hist” step
  • One language, one dependency manifest, one cargo run
  • Output is SVG or PNG with deterministic, reproducible bytes
  • Plays nicely with HPC: no display server, no interactive backend

The three libraries you might compare

Library Language Style One-line summary
matplotlib Python imperative mature, huge API, the default
ggplot2 R declarative grammar layered, tidy data in, plot out
plotters Rust imperative builder small, fast, SVG/PNG only

Anatomy of a chart

The parts shown in the figure below:

  • title at the top
  • drawing area (the whole canvas, including margins)
  • chart area (the inner box where the data lives)
  • axes with axis ticks (the marks on each axis)
  • axis labels (“read length”, “count”)
  • series — the actual marks (bars, points, lines)
  • legend — names each series
A labelled diagram of a generic chart showing a chart title at the top, a drawing area margin around the outside, the chart area inside it containing axes (x-axis with ticks and labels at the bottom, y-axis with ticks and labels at the left), axis labels, two data series rendered as bars and points, and a legend in the upper right.

A generic chart has the same labelled pieces in every library.

A histogram in three languages

Three panels side by side, each showing the same read-length histogram with about six bars peaking near 100. The panels are labelled matplotlib (Python), ggplot2 (R), and plotters (Rust). Below each panel is a six-line code snippet in the corresponding language.

Same data, same shape — three different toolchains produce the same picture.

# matplotlib (Python)
plt.hist(lengths, bins=30)
plt.xlabel("read length"); plt.ylabel("count")
plt.savefig("readlen.png")
# ggplot2 (R)
ggplot(df, aes(x = length)) +
  geom_histogram(bins = 30) +
  ggsave("readlen.png")
// plotters (Rust) — abridged; full version on a later slide
let root = SVGBackend::new("readlen.svg", (800, 600)).into_drawing_area();
let mut chart = ChartBuilder::on(&root).build_cartesian_2d(0u32..30, 0u32..max)?;
chart.draw_series(bars_for(&counts))?;
root.present()?;

The plotters mental model

A backend is the rendering target — the thing that turns drawing calls into bytes (here: SVG XML or a PNG bitmap). A drawing area is the whole canvas (the pixels that will become the file). A series is one set of marks (bars, points, a line).

Three nested rounded rectangles. The outer box is labelled DrawingArea (the canvas), with a small caption 'SVGBackend or BitMapBackend'. Inside it is a smaller box labelled ChartContext (axes plus coordinate system), with caption 'built by ChartBuilder::on(&root)'. Inside that is the innermost box labelled Series (the marks), with caption 'Rectangle, Circle, PathElement, ...'. To the right is a code panel showing the three lines that build each layer: SVGBackend::new(...).into_drawing_area(), ChartBuilder::on(&root).build_cartesian_2d(...), chart.draw_series(...).

Three nested concepts: a DrawingArea, a ChartContext inside it, and Series drawn into the chart.

plotters — the four-line skeleton

use plotters::prelude::*;

let root = SVGBackend::new("readlen.svg", (800, 600))      // 1. backend + size
    .into_drawing_area();                                  //    wrap as a DrawingArea
root.fill(&WHITE)?;                                        //    paint background white

let mut chart = ChartBuilder::on(&root)                    // 2. start a chart
    .caption("Read length", ("sans-serif", 24))            //    title at the top
    .build_cartesian_2d(0u32..30, 0u32..max)?;             // 3. fix the coordinate system
chart.configure_mesh().draw()?;                            //    draw axes + gridlines

// (series go here — next slide)

root.present()?;                                           // 4. flush to disk

Four steps: backend → drawing area → chart → present. The series come next.

A chart rectangle showing the drawing area boundary, the x-axis along the bottom with ticks 0, 50, 100, 150, 200, 250, and the y-axis along the left with ticks 0, 5, 10, 15, the origin at bottom-left labelled (0, 0), axis labels 'read length (bp)' and 'count', and an annotation pointing at the interior labelled 'data coordinates — pass (x, y) tuples to draw_series, plotters places them in pixels for you'.

Every plotters chart is a rectangle in pixel space; once you call build_cartesian_2d, it becomes a rectangle in your data coordinates. Everything you draw afterwards is in those data units.

plotters — draw_series with one rectangle per bar

chart.draw_series(counts.iter().enumerate().map(           // for each (bin, count)
    |(b, &c)| Rectangle::new(                              // build a Rectangle
        [(b as u32, 0), (b as u32 + 1, c)],                // corners: (x0,y0)-(x1,y1)
        BLUE.filled(),                                     // fill style
    ),
))?;

The closure |(b, &c)| Rectangle::new(...) turns each (bin_index, count) pair into one bar. draw_series consumes the resulting iterator and renders every bar.

A single histogram bar shown enlarged. Two corner points labelled: bottom-left at coordinates (bin_x_start, 0), top-right at (bin_x_end, count). Arrows from each corner to the corresponding part of the Rectangle::new(...) call. Annotation: each bar is one Rectangle; the closure maps bin (b, c) to those two corners.

Each Rectangle::new takes two corner points in data coordinates: bottom-left at (bin_x_start, 0) and top-right at (bin_x_end, count). plotters does the pixel arithmetic.

A scatter plot — adding marks

use plotters::prelude::*;

let points: Vec<(f64, f64)> = vec![
    (1.0, 2.1), (2.0, 1.9), (3.0, 3.2), (4.0, 4.0), (5.0, 5.1),
];

let root = SVGBackend::new("scatter.svg", (640, 480)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .margin(20).x_label_area_size(35).y_label_area_size(40)
    .build_cartesian_2d(0.0..6.0, 0.0..6.0)?;
chart.configure_mesh().draw()?;
chart.draw_series(points.iter().map(|&(x, y)|
    Circle::new((x, y), 4, RED.filled())))?;     // one Circle per point
root.present()?;

Circle::new takes a centre, a radius in pixels, and a style. Like plt.scatter(x, y) or geom_point() — same idea, hand-rolled.

A line plot — connecting points

let series: Vec<(f64, f64)> = (0..100)
    .map(|i| {
        let x = i as f64 * 0.1;
        (x, x.sin())                                   // y = sin(x)
    })
    .collect();

let root = SVGBackend::new("line.svg", (640, 480)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .margin(20).x_label_area_size(35).y_label_area_size(40)
    .build_cartesian_2d(0.0..10.0, -1.2..1.2)?;
chart.configure_mesh().draw()?;
chart.draw_series(LineSeries::new(series, &BLUE))?;     // one connected line
root.present()?;

LineSeries::new takes an iterator of (x, y) and a style. Equivalent to plt.plot(x, y) or geom_line().

A sine wave from x=0 to x=2π drawn as 24 connected line segments. Each of the 24 sample points marked with a small dot, the line connecting them shown above. Annotation: 'each line segment connects two consecutive (x, y) tuples — more points = smoother curve'.

A line plot is just N points connected in order. Compute the (x, y) tuples in Rust, hand them to LineSeries; plotters draws the segments between them.

Multiple series on one chart

let xs: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
let s1: Vec<(f64, f64)> = xs.iter().map(|&x| (x, x.sin())).collect();
let s2: Vec<(f64, f64)> = xs.iter().map(|&x| (x, x.cos())).collect();

chart.draw_series(LineSeries::new(s1, &RED))?
    .label("sin(x)")                                       // legend entry
    .legend(|(x, y)| PathElement::new(                     // (x,y) = pixel of legend swatch
        vec![(x, y), (x + 20, y)], RED));                  //   draw a 20-pixel red line

chart.draw_series(LineSeries::new(s2, &BLUE))?
    .label("cos(x)")
    .legend(|(x, y)| PathElement::new(                     // same idea, blue swatch
        vec![(x, y), (x + 20, y)], BLUE));

chart.configure_series_labels()
    .background_style(&WHITE.mix(0.8))
    .border_style(&BLACK)
    .draw()?;                                              // render the legend box
A line chart with two series: debug-mode timings as a red line rising steeply, release-mode timings as a green line rising gently. X-axis: input size. Y-axis: wall-clock seconds. Legend in upper-left labels each line.

The same chart with two series overlaid — debug-mode and release-mode timings as a function of input size — and a legend in the upper-left distinguishing them.

Saving to SVG vs PNG

Vector = stored as shapes (lines, circles) that scale cleanly to any size. Raster (also called bitmap) = stored as a fixed grid of pixels; zooming in shows the squares.

Backend Output When to use
SVGBackend vector XML papers, posters, slides — scales without blurring
BitMapBackend PNG bitmap (raster) screenshots, dashboards, large data with millions of marks
let svg = SVGBackend::new("out.svg", (800, 600)).into_drawing_area();
let png = BitMapBackend::new("out.png", (800, 600)).into_drawing_area();
// ...everything after this point is identical

PNG requires a small amount of platform setup — cairo on Linux, otherwise the pure-Rust rasteriser. SVG works everywhere with no extras.

Side-by-side comparison: a small chart rendered as SVG on the left, sharp at any size; the same chart rendered as a 100-pixel-wide PNG on the right and then enlarged 4×, showing visible pixel blocks. Annotation: 'vector = math, scalable; raster = grid of pixels, fixed resolution'.

Same chart, two formats: the SVG stays sharp at any zoom (vector); the low-resolution PNG pixelates when enlarged (raster, fixed grid of pixels).

One practical reason to prefer SVG for figures you’ll iterate on: you can open the file in Inkscape (a free vector-graphics editor) and tweak labels, colours, or layout by hand without re-running your pipeline. Final-figure polish — moving a legend, adding a callout arrow — is far faster in Inkscape than in plotters code.

Styling — colour, stroke, alpha

Alpha = transparency (0.0 = fully transparent, 1.0 = fully opaque). In plotters it is set with .mix(alpha).

// Translucent fill — useful for overlapping bars or points
Rectangle::new([(0, 0), (1, 10)], RED.mix(0.5).filled());

// Thicker stroke — useful for lines that need to stand out
LineSeries::new(series, BLUE.stroke_width(2));

// Custom RGB — decimal r, g, b in 0..=255
let teal = RGBColor(31, 119, 180);
Circle::new((x, y), 4, teal.filled());
Three small charts stacked vertically. Each pair shows 'before' on the left and 'after' on the right. Top pair: same scatter, points red on left and blue on right. Middle pair: same line, thin on left and thick on right. Bottom pair: same overlapping scatter, opaque on left (occluding) and semi-transparent on right (overlap visible). Each pair labelled with the one styling attribute that changed.

Three minimal-pair examples: same chart, one thing changed in each. Top: colour swap (red → blue). Middle: stroke width (1 px → 3 px). Bottom: alpha (1.0 → 0.4 — translucent so overlapping points are visible).

Multi-panel charts — one image, four conditions

Say you want to compare GC content across four sequencing samples — one chart per sample, side by side. You don’t want four separate files; you want one image you can drop in a paper or report.

split_evenly divides the drawing area into a grid; each cell is itself a drawing area you can build a chart on:

let root = SVGBackend::new("samples.svg", (1200, 900)).into_drawing_area();
root.fill(&WHITE)?;
let areas = root.split_evenly((2, 2));  // 2 rows × 2 cols

for (area, sample) in areas.iter().zip(samples.iter()) {
    let mut chart = ChartBuilder::on(area)
        .caption(&sample.name, ("sans-serif", 18))
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(40)
        .build_cartesian_2d(0.0..1.0, 0..50)?;
    chart.draw_series(...)?;  // GC histogram for this sample
}

Four charts, one SVG, three lines of layout code. Same trick: split_horizontally(50) for a 50:50 left/right split, split_vertically(...) for top/bottom.

A scatter for the exercise

// Mean quality vs read length, one point per FASTQ record.
let points: Vec<(f64, f64)> = records.iter()
    .map(|r| (r.length as f64, r.mean_quality))
    .collect();

// max_len: the largest x (length) across all points
let max_len = points.iter()
    .map(|p| p.0)                                 // take just the x coordinate
    .fold(0.0_f64, f64::max);                     // running max, starting at 0.0
let root = SVGBackend::new("qc.svg", (800, 600)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .caption("Quality vs length", ("sans-serif", 22))
    .margin(20).x_label_area_size(40).y_label_area_size(40)
    .build_cartesian_2d(0.0..max_len, 0.0..45.0)?;
chart.configure_mesh().x_desc("length").y_desc("mean Q").draw()?;
chart.draw_series(points.iter().map(|&(x, y)|
    Circle::new((x, y), 2, BLUE.mix(0.3).filled())))?;
root.present()?;
A scatter plot with x-axis labelled 'read index (0..1000)' from 0 to 1000 and y-axis labelled 'read length (bp)' from 0 to 300. Points scattered mostly around 150 bp with a tail of shorter reads. Title: 'Read lengths — 1000 reads'.

Output of the scatter exercise on a sample of read lengths: each point is one read at (position, length), with the y-axis showing the length distribution at a glance.

To the exercise

cd day4/ex-plot-readlen
cargo test
cargo run -- 5 readlen.png