Skip to main content

faceted/
faceted.rs

1use ggplot_rs::prelude::*;
2use polars::prelude::*;
3
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    // Generate data with two grouping variables
6    let sepal_length: Vec<f64> = (0..120)
7        .map(|i| 4.0 + (i as f64) * 0.04 + (i as f64 * 0.5).sin() * 0.3)
8        .collect();
9    let sepal_width: Vec<f64> = (0..120)
10        .map(|i| 2.0 + (i as f64) * 0.015 + (i as f64 * 0.3).cos() * 0.4)
11        .collect();
12    let species: Vec<&str> = (0..120)
13        .map(|i| match i % 3 {
14            0 => "setosa",
15            1 => "versicolor",
16            _ => "virginica",
17        })
18        .collect();
19    let region: Vec<&str> = (0..120)
20        .map(|i| if i % 2 == 0 { "North" } else { "South" })
21        .collect();
22
23    let df = df! {
24        "sepal_length" => sepal_length,
25        "sepal_width" => sepal_width,
26        "species" => species,
27        "region" => region,
28    }?;
29
30    // facet_wrap: one variable, automatic grid layout
31    GGPlot::new(df.clone())
32        .aes(
33            Aes::new()
34                .x("sepal_length")
35                .y("sepal_width")
36                .color("species"),
37        )
38        .geom_point()
39        .facet_wrap("species", Some(2))
40        .title("Facet Wrap by Species")
41        .xlab("Sepal Length")
42        .ylab("Sepal Width")
43        .save("facet_wrap.svg")?;
44
45    println!("Saved facet_wrap.svg");
46
47    // facet_grid: two variables, row ~ col layout
48    GGPlot::new(df)
49        .aes(
50            Aes::new()
51                .x("sepal_length")
52                .y("sepal_width")
53                .color("species"),
54        )
55        .geom_point()
56        .facet_grid(Some("region"), Some("species"))
57        .title("Facet Grid: Region ~ Species")
58        .xlab("Sepal Length")
59        .ylab("Sepal Width")
60        .save("facet_grid.svg")?;
61
62    println!("Saved facet_grid.svg");
63    Ok(())
64}