Skip to main content

crisol_plot/plot/
dataset.rs

1//! Plots bound to dataset columns: `Plot::from_dataset(&data).x("t").y("v")`.
2
3use egui::{Color32, Ui};
4
5use super::{Bounds, Plot, PlotResponse, PlotState, Series};
6use crisol_core::data::{Dataset, LinkHub, LinkMode};
7use crisol_ui_kit::Icons;
8
9/// How a dataset series is drawn.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum DatasetPlotKind {
13    /// A line through the points.
14    #[default]
15    Line,
16    /// One marker per point.
17    Scatter,
18}
19
20/// A plot builder over two numeric dataset columns.
21pub struct DatasetPlot<'a> {
22    data: &'a Dataset,
23    x: String,
24    y: Option<String>,
25    color_by: Option<String>,
26    title: Option<String>,
27    kind: DatasetPlotKind,
28    height: f32,
29    visible: Option<Vec<usize>>,
30}
31
32impl<'a> DatasetPlot<'a> {
33    /// A line plot over `x` and `y`.
34    pub fn new(data: &'a Dataset, x: impl Into<String>, y: Option<impl Into<String>>) -> Self {
35        Self {
36            data,
37            x: x.into(),
38            y: y.map(Into::into),
39            color_by: None,
40            title: None,
41            kind: DatasetPlotKind::Line,
42            height: 260.0,
43            visible: None,
44        }
45    }
46
47    /// Set the x column.
48    pub fn x(mut self, x: impl Into<String>) -> Self {
49        self.x = x.into();
50        self
51    }
52
53    /// Set the y column.
54    pub fn y(mut self, y: impl Into<String>) -> Self {
55        self.y = Some(y.into());
56        self
57    }
58
59    /// Split the series by a text/category column.
60    pub fn color_by(mut self, column: impl Into<String>) -> Self {
61        self.color_by = Some(column.into());
62        self
63    }
64
65    /// Set the title.
66    pub fn title(mut self, title: impl Into<String>) -> Self {
67        self.title = Some(title.into());
68        self
69    }
70
71    /// Draw markers instead of a line.
72    pub fn scatter(mut self) -> Self {
73        self.kind = DatasetPlotKind::Scatter;
74        self
75    }
76
77    /// Set the height.
78    pub fn height(mut self, height: f32) -> Self {
79        self.height = height;
80        self
81    }
82
83    /// The rows whose x and y values fall inside `bounds`.
84    pub fn rows_in(&self, bounds: Bounds) -> Vec<usize> {
85        let Some(y) = &self.y else {
86            return Vec::new();
87        };
88        self.data.rows_in_bounds(&self.x, y, bounds)
89    }
90
91    /// Show only `rows` of the dataset.
92    pub fn with_rows(mut self, rows: impl IntoIterator<Item = usize>) -> Self {
93        self.visible = Some(rows.into_iter().collect());
94        self
95    }
96
97    /// Show the plot and publish its brush to a selection bus.
98    pub fn show_linked(
99        mut self,
100        ui: &mut Ui,
101        icons: &mut Icons,
102        state: &mut PlotState,
103        hub: &mut LinkHub,
104    ) -> PlotResponse {
105        if hub.mode() != LinkMode::Highlight && !hub.selection().is_empty() {
106            self.visible = Some(hub.selection().rows.iter().copied().collect());
107        }
108        let selected_rows = state.selection.map(|selection| self.rows_in(selection));
109        let response = self.show(ui, icons, state);
110        if let Some(rows) = selected_rows {
111            hub.set_rows(rows, "plot");
112        } else if hub.selection().source.as_deref() == Some("plot") {
113            hub.clear();
114        }
115        response
116    }
117
118    /// Show the plot.
119    pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
120        let Some(y) = self.y.as_deref() else {
121            return Plot::new("dataset-empty").height(self.height).show(ui, icons, state);
122        };
123        let palette = [
124            Color32::from_rgb(0x58, 0xa6, 0xff),
125            Color32::from_rgb(0xf7, 0x78, 0xba),
126            Color32::from_rgb(0x3f, 0xd0, 0x8a),
127            Color32::from_rgb(0xe3, 0xb3, 0x41),
128            Color32::from_rgb(0xb0, 0x8c, 0xff),
129            Color32::from_rgb(0x56, 0xd4, 0xdd),
130        ];
131        let mut groups: Vec<(String, Vec<[f64; 2]>)> = Vec::new();
132        let rows: Vec<usize> = self
133            .visible
134            .clone()
135            .unwrap_or_else(|| (0..self.data.row_count()).collect());
136        if let Some(color_by) = &self.color_by
137            && let Some(column) = self.data.column_named(color_by)
138        {
139            for row in rows {
140                let Some([x, y]) = self.data.point_at_row(&self.x, y, row) else {
141                    continue;
142                };
143                let key = column.cell(row).to_text();
144                if let Some((_, points)) = groups.iter_mut().find(|(name, _)| name == &key) {
145                    points.push([x, y]);
146                } else {
147                    groups.push((key, vec![[x, y]]));
148                }
149            }
150        } else {
151            let points: Vec<[f64; 2]> = rows
152                .into_iter()
153                .filter_map(|row| self.data.point_at_row(&self.x, y, row))
154                .collect();
155            groups.push((y.to_owned(), points));
156        }
157        let mut plot = Plot::new("dataset").x_label(&self.x).y_label(y).height(self.height);
158        if let Some(title) = &self.title {
159            plot = plot.title(title);
160        }
161        for (index, (name, points)) in groups.iter().enumerate() {
162            let series = match self.kind {
163                DatasetPlotKind::Line => Series::line(name.clone(), points.as_slice()),
164                DatasetPlotKind::Scatter => Series::scatter(name.clone(), points.as_slice()),
165            };
166            plot = plot.series(series.color(palette[index % palette.len()]));
167        }
168        plot.show(ui, icons, state)
169    }
170}
171
172impl Plot<'_> {
173    /// Start a plot bound to dataset columns.
174    pub fn from_dataset(data: &Dataset) -> DatasetPlot<'_> {
175        DatasetPlot::new(data, "", None::<String>)
176    }
177}