// plotters (Rust) — abridged; full version on a later slidelet root =SVGBackend::new("readlen.svg", (800,600)).into_drawing_area();letmut 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 concepts: a DrawingArea, a ChartContext inside it, and Series drawn into the chart.
plotters — the four-line skeleton
useplotters::prelude::*;let root =SVGBackend::new("readlen.svg", (800,600)) // 1. backend + size.into_drawing_area();// wrap as a DrawingArearoot.fill(&WHITE)?;// paint background whiteletmut 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 systemchart.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.
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 asu32,0), (b asu32+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.
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
useplotters::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)?;letmut 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 pointroot.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 asf64*0.1; (x, x.sin()) // y = sin(x)}).collect();let root =SVGBackend::new("line.svg", (640,480)).into_drawing_area();root.fill(&WHITE)?;letmut 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 lineroot.present()?;
LineSeries::new takes an iterator of (x, y) and a style. Equivalent to plt.plot(x, y) or geom_line().
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 asf64*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 swatchvec![(x, y), (x +20, y)], RED));// draw a 20-pixel red linechart.draw_series(LineSeries::new(s2,&BLUE))?.label("cos(x)").legend(|(x, y)|PathElement::new( // same idea, blue swatchvec![(x, y), (x +20, y)], BLUE));chart.configure_series_labels().background_style(&WHITE.mix(0.8)).border_style(&BLACK).draw()?;// render the legend box
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.
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.
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 pointsRectangle::new([(0,0), (1,10)], RED.mix(0.5).filled());// Thicker stroke — useful for lines that need to stand outLineSeries::new(series, BLUE.stroke_width(2));// Custom RGB — decimal r, g, b in 0..=255let teal = RGBColor(31,119,180);Circle::new((x, y),4, teal.filled());
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 colsfor (area, sample) in areas.iter().zip(samples.iter()) {letmut 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 asf64, r.mean_quality)).collect();// max_len: the largest x (length) across all pointslet max_len = points.iter().map(|p| p.0) // take just the x coordinate.fold(0.0_f64,f64::max);// running max, starting at 0.0let root =SVGBackend::new("qc.svg", (800,600)).into_drawing_area();root.fill(&WHITE)?;letmut 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()?;
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.