scatterplot/
scatterplot.rs

1use polars::prelude::*;
2
3use plotlars::{Axis, Legend, Plot, Rgb, ScatterPlot, Shape, Text, TickDirection};
4
5fn main() {
6    let dataset = LazyCsvReader::new(PlPath::new("data/penguins.csv"))
7        .finish()
8        .unwrap()
9        .select([
10            col("species"),
11            col("sex").alias("gender"),
12            col("flipper_length_mm").cast(DataType::Int16),
13            col("body_mass_g").cast(DataType::Int16),
14        ])
15        .collect()
16        .unwrap();
17
18    let axis = Axis::new()
19        .show_line(true)
20        .tick_direction(TickDirection::OutSide)
21        .value_thousands(true);
22
23    ScatterPlot::builder()
24        .data(&dataset)
25        .x("body_mass_g")
26        .y("flipper_length_mm")
27        .group("species")
28        .sort_groups_by(|a, b| {
29            if a.len() == b.len() {
30                a.cmp(b)
31            } else {
32                a.len().cmp(&b.len())
33            }
34        }) //sort by length unless equal length then lexical
35        .opacity(0.5)
36        .size(12)
37        .colors(vec![Rgb(178, 34, 34), Rgb(65, 105, 225), Rgb(255, 140, 0)])
38        .shapes(vec![Shape::Circle, Shape::Square, Shape::Diamond])
39        .plot_title(Text::from("Scatter Plot").font("Arial").size(20).x(0.065))
40        .x_title("body mass (g)")
41        .y_title("flipper length (mm)")
42        .legend_title("species")
43        .x_axis(&axis.clone().value_range(vec![2500.0, 6500.0]))
44        .y_axis(&axis.clone().value_range(vec![170.0, 240.0]))
45        .legend(&Legend::new().x(0.85).y(0.15))
46        .build()
47        .plot();
48}