Exercise: Plot a read-length histogram with plotters

Goal

Given a vector of read lengths, produce a histogram as a PNG file using the plotters crate:

fn plot_histogram(lengths: &[usize], bin_width: usize, output_path: &Path) -> Result<(), Box<dyn std::error::Error>>

This is your first plot in Rust. plotters is an imperative builder API (compared to ggplot2’s grammar of graphics), but the conceptual pieces are the same: a drawing surface, axes with scales, a chart, and one or more data series.

The crate

[dependencies]
plotters = "0.3"

plotters ships a prelude module that brings most of what you need into scope with one use:

use plotters::prelude::*;

You will see:

The exercise

cd day4/ex-plot-readlen

Make the two tests pass — they call your function with synthetic data and check that (a) it produces a non-empty PNG file at the requested path, (b) the PNG starts with the standard PNG magic bytes.

How to run

cargo test
cargo run -- 5 readlen.png    # synthetic data, bin width 5, output readlen.png

Hints

Group the lengths into bins of the given width. The histogram bar at position b covers lengths b * bin_width..(b+1) * bin_width:

let max = *lengths.iter().max().unwrap_or(&0);
let n_bins = max / bin_width + 1;
let mut counts: Vec<u32> = vec![0; n_bins];
for &l in lengths {
    counts[l / bin_width] += 1;
}
let max_count = *counts.iter().max().unwrap_or(&0);
let root = BitMapBackend::new(output_path, (800, 600)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .caption("Read length distribution", ("sans-serif", 30))
    .margin(20)
    .x_label_area_size(40)
    .y_label_area_size(50)
    .build_cartesian_2d(0u32..(n_bins as u32 * bin_width as u32), 0u32..(max_count + 1))?;
chart.configure_mesh()
    .x_desc("read length")
    .y_desc("count")
    .draw()?;

Each bar is a Rectangle from (b * bin_width, 0) to ((b+1) * bin_width, count):

chart.draw_series(counts.iter().enumerate().map(|(b, &c)| {
    let x0 = (b * bin_width) as u32;
    let x1 = ((b + 1) * bin_width) as u32;
    Rectangle::new([(x0, 0u32), (x1, c)], BLUE.mix(0.6).filled())
}))?;
root.present()?;

BLUE.mix(0.6) gives a slightly translucent blue; .filled() fills the rectangle rather than just outlining it.

Solution

See day4/ex-plot-readlen-solution/src/main.rs for the full reference. The whole function is about 25 lines.

Where this leads

  • Swap BitMapBackend for SVGBackend and the output is SVG with no other changes.
  • The plotters::series::Histogram type can replace the draw_series(... Rectangle ...) loop, but it requires the same kinds of inputs and is not significantly shorter for this case.
  • Read FASTQ records with noodles-fastq, collect their lengths into a Vec<usize>, and feed the result into plot_histogram. That is the production version of this exercise.