How to Plot Data from Rust (plotters crate)

Plot data in Rust using the plotters crate by creating a bitmap backend, configuring a chart area, and drawing series.

Use the plotters crate to create a bitmap backend, configure a chart, and draw your data points as a line or scatter plot. The following example creates a PNG file containing a simple line chart from a vector of data points.

use plotters::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = BitMapBackend::new("plot.png", (640, 480)).into_drawing_area();
    root.fill(&WHITE)?;
    let mut chart = ChartBuilder::on(&root)
        .caption("Sample Plot Title", ("sans-serif", 30).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(30)
        .build_cartesian_2d(0f32..10f32, 0f32..10f32)?;

    chart.configure_mesh().draw()?;
    chart.draw_series(LineSeries::new(
        vec![(1f32, 2f32), (2f32, 4f32), (3f32, 8f32)],
        &RED,
    ))?;

    Ok(())
}

Add plotters = "0.3" to your Cargo.toml dependencies to use this code.