Skip to main content

ggplot_rs/geom/
smooth.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::{DataFrame, Value};
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, LineStyle, Linetype, PointShape, PointStyle, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::smooth::{SmoothMethod, StatSmooth};
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Smooth line with optional confidence ribbon.
16pub struct GeomSmooth {
17    pub color: (u8, u8, u8),
18    pub fill: (u8, u8, u8),
19    pub line_width: f64,
20    pub alpha: f64,
21    pub se: bool,
22    pub n_points: usize,
23    pub method: SmoothMethod,
24}
25
26impl Default for GeomSmooth {
27    fn default() -> Self {
28        GeomSmooth {
29            color: (51, 102, 204),
30            fill: (51, 102, 204),
31            line_width: 1.5,
32            alpha: 0.2,
33            se: true,
34            n_points: 80,
35            method: SmoothMethod::Lm,
36        }
37    }
38}
39
40impl GeomSmooth {
41    /// Use LOESS smoothing with the given span.
42    pub fn loess(mut self, span: f64) -> Self {
43        self.method = SmoothMethod::Loess { span };
44        self
45    }
46
47    /// Use penalized B-spline (P-spline) GAM smoothing — ggplot2's
48    /// `method = "gam"`, with λ chosen by GCV. Backed by anofox-regression's
49    /// `PSplineRegressor` when the `regression` feature is enabled; a small
50    /// dependency-free (wasm-safe) P-spline fit otherwise — both track the
51    /// same curve (#174).
52    pub fn gam(mut self) -> Self {
53        self.method = SmoothMethod::Gam;
54        self
55    }
56
57    /// Use a generalized linear model — ggplot2's
58    /// `geom_smooth(method = "glm", method.args = list(family = …))` — e.g.
59    /// `GeomSmooth::default().glm(SmoothFamily::binomial())`. The band is the
60    /// link-scale confidence interval mapped through the inverse link (see
61    /// [`SmoothFamily`](crate::stat::smooth::SmoothFamily)).
62    #[cfg(feature = "regression")]
63    pub fn glm(mut self, family: crate::stat::smooth::SmoothFamily) -> Self {
64        self.method = SmoothMethod::Glm { family };
65        self
66    }
67}
68
69impl Geom for GeomSmooth {
70    fn draw(
71        &self,
72        data: &DataFrame,
73        coord: &dyn Coord,
74        scales: &ScaleSet,
75        _theme: &Theme,
76        backend: &mut dyn DrawBackend,
77    ) -> Result<(), RenderError> {
78        let x_col = data
79            .column("x")
80            .ok_or(RenderError::MissingAesthetic("x".into()))?;
81        let y_col = data
82            .column("y")
83            .ok_or(RenderError::MissingAesthetic("y".into()))?;
84        let ymin_col = data.column("ymin");
85        let ymax_col = data.column("ymax");
86        let color_col = data.column("color");
87        let fill_col = data.column("fill");
88
89        let plot_area = backend.plot_area();
90        let x_scale = scales.get(&Aesthetic::X);
91        let y_scale = scales.get(&Aesthetic::Y);
92
93        // If there's a color/fill aesthetic, draw separate smooths per group
94        if let Some(cc) = color_col.or(fill_col) {
95            let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
96            for (i, v) in cc.iter().enumerate() {
97                let key = v.to_group_key();
98                if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
99                    entry.1.push(i);
100                } else {
101                    groups.push((key, vec![i]));
102                }
103            }
104
105            for (_, indices) in &groups {
106                let first_idx = indices[0];
107
108                // Determine colors from mapped aesthetics
109                let line_color = color_col
110                    .and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
111                    .unwrap_or(self.color);
112                let ribbon_fill = fill_col
113                    .and_then(|f| scales.map_color(&Aesthetic::Fill, &f[first_idx]))
114                    .or_else(|| {
115                        color_col.and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
116                    })
117                    .unwrap_or(self.fill);
118
119                // Draw confidence ribbon
120                if self.se {
121                    if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
122                        let mut upper_points: Vec<(f64, f64)> = Vec::new();
123                        let mut lower_points: Vec<(f64, f64)> = Vec::new();
124
125                        for &i in indices {
126                            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
127                            let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
128                            let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
129
130                            upper_points.push(coord.transform((nx, ny_max), &plot_area));
131                            lower_points.push(coord.transform((nx, ny_min), &plot_area));
132                        }
133
134                        let mut polygon = upper_points;
135                        lower_points.reverse();
136                        polygon.extend(lower_points);
137
138                        if polygon.len() >= 3 {
139                            backend.draw_polygon(
140                                &polygon,
141                                &RectStyle {
142                                    fill: Some(ribbon_fill),
143                                    stroke: None,
144                                    stroke_width: 0.0,
145                                    alpha: self.alpha,
146                                    clip: true,
147                                    corner_radius: 0.0,
148                                },
149                            )?;
150                        }
151                    }
152                }
153
154                // Draw fitted line
155                let points: Vec<(f64, f64)> = indices
156                    .iter()
157                    .map(|&i| {
158                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
159                        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
160                        coord.transform((nx, ny), &plot_area)
161                    })
162                    .collect();
163
164                if points.len() >= 2 {
165                    backend.draw_line(
166                        &points,
167                        &LineStyle {
168                            color: line_color,
169                            alpha: 1.0,
170                            width: self.line_width,
171                            linetype: Linetype::Solid,
172                            ..Default::default()
173                        },
174                    )?;
175                    draw_hover_marks(
176                        backend, scales, &points, indices, x_col, y_col, ymin_col, ymax_col,
177                        line_color,
178                    )?;
179                }
180            }
181        } else {
182            // No grouping — original behavior with fixed colors
183
184            // Draw confidence ribbon first (behind line)
185            if self.se {
186                if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
187                    let mut upper_points: Vec<(f64, f64)> = Vec::new();
188                    let mut lower_points: Vec<(f64, f64)> = Vec::new();
189
190                    for i in 0..data.nrows() {
191                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
192                        let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
193                        let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
194
195                        upper_points.push(coord.transform((nx, ny_max), &plot_area));
196                        lower_points.push(coord.transform((nx, ny_min), &plot_area));
197                    }
198
199                    // Build polygon: upper left-to-right, then lower right-to-left
200                    let mut polygon = upper_points;
201                    lower_points.reverse();
202                    polygon.extend(lower_points);
203
204                    if polygon.len() >= 3 {
205                        backend.draw_polygon(
206                            &polygon,
207                            &RectStyle {
208                                fill: Some(self.fill),
209                                stroke: None,
210                                stroke_width: 0.0,
211                                alpha: self.alpha,
212                                clip: true,
213                                corner_radius: 0.0,
214                            },
215                        )?;
216                    }
217                }
218            }
219
220            // Draw fitted line
221            let points: Vec<(f64, f64)> = (0..data.nrows())
222                .map(|i| {
223                    let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
224                    let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
225                    coord.transform((nx, ny), &plot_area)
226                })
227                .collect();
228
229            if points.len() >= 2 {
230                backend.draw_line(
231                    &points,
232                    &LineStyle {
233                        color: self.color,
234                        alpha: 1.0,
235                        width: self.line_width,
236                        linetype: Linetype::Solid,
237                        ..Default::default()
238                    },
239                )?;
240                let rows: Vec<usize> = (0..data.nrows()).collect();
241                draw_hover_marks(
242                    backend, scales, &points, &rows, x_col, y_col, ymin_col, ymax_col, self.color,
243                )?;
244            }
245        }
246
247        Ok(())
248    }
249
250    fn required_aes(&self) -> Vec<Aesthetic> {
251        vec![Aesthetic::X, Aesthetic::Y]
252    }
253
254    fn default_stat(&self) -> Box<dyn Stat> {
255        Box::new(StatSmooth {
256            n_points: self.n_points,
257            se: self.se,
258            method: self.method.clone(),
259        })
260    }
261
262    fn default_position(&self) -> Box<dyn Position> {
263        Box::new(PositionIdentity)
264    }
265
266    fn default_params(&self) -> GeomParams {
267        GeomParams::default()
268    }
269
270    fn name(&self) -> &str {
271        "smooth"
272    }
273
274    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
275        const DEFAULT: (u8, u8, u8) = (51, 102, 204);
276        if let (true, Some(accent)) = (self.color == DEFAULT, el.accent) {
277            self.color = accent;
278        }
279        if let (true, Some(accent)) = (self.fill == DEFAULT, el.accent) {
280            self.fill = accent;
281        }
282    }
283
284    fn set_series_color(&mut self, color: (u8, u8, u8)) {
285        self.color = color;
286        self.fill = color;
287    }
288}
289
290/// The fitted curve is drawn as a single path and so carries no per-point
291/// marks. Emit a sparse set of transparent hover points along it — each tagged
292/// with the fitted `ŷ` (and the CI when present) — so the axis pointer can read
293/// the smoother on hover, mirroring `geom_density`.
294#[allow(clippy::too_many_arguments)]
295fn draw_hover_marks(
296    backend: &mut dyn DrawBackend,
297    scales: &ScaleSet,
298    points: &[(f64, f64)],
299    rows: &[usize],
300    x_col: &[Value],
301    y_col: &[Value],
302    ymin_col: Option<&[Value]>,
303    ymax_col: Option<&[Value]>,
304    color: (u8, u8, u8),
305) -> Result<(), RenderError> {
306    let step = (rows.len() / 40).max(1);
307    for (k, &i) in rows.iter().enumerate() {
308        if k % step != 0 {
309            continue;
310        }
311        super::set_mark(
312            backend,
313            Some(smooth_tip(y_col, ymin_col, ymax_col, i)),
314            Some(super::tip_value(&x_col[i])),
315            None,
316            super::raw_value(&y_col[i]),
317        );
318        super::set_mark_formatted(
319            backend,
320            scales,
321            Some(&x_col[i]),
322            &Aesthetic::Y,
323            Some(&y_col[i]),
324        );
325        backend.draw_shape(
326            points[k],
327            0.6,
328            &PointStyle {
329                color,
330                alpha: 0.0,
331                filled: true,
332                shape: PointShape::Circle,
333            },
334        )?;
335    }
336    super::clear_mark(backend);
337    Ok(())
338}
339
340/// `ŷ = <fitted>` plus ` [lo, hi]` when a confidence band is present.
341fn smooth_tip(
342    y_col: &[Value],
343    ymin_col: Option<&[Value]>,
344    ymax_col: Option<&[Value]>,
345    i: usize,
346) -> String {
347    let yv = y_col[i]
348        .as_f64()
349        .map(|f| format!("{f:.3}"))
350        .unwrap_or_default();
351    let ci = match (ymin_col, ymax_col) {
352        (Some(lo), Some(hi)) => match (lo[i].as_f64(), hi[i].as_f64()) {
353            (Some(a), Some(b)) => format!(" [{a:.3}, {b:.3}]"),
354            _ => String::new(),
355        },
356        _ => String::new(),
357    };
358    format!("ŷ = {yv}{ci}")
359}