Skip to main content

ggplot_rs/geom/
density_ridges.rs

1//! Ridgeline plot (`geom_density_ridges`, anofox-visualization#917): one
2//! density per group of a discrete y, drawn upward from the group's
3//! baseline and overlapping the next row — distributions over time.
4use std::collections::HashMap;
5
6use crate::aes::Aesthetic;
7use crate::coord::Coord;
8use crate::data::DataFrame;
9use crate::position::identity::PositionIdentity;
10use crate::position::Position;
11use crate::render::backend::{DrawBackend, RectStyle};
12use crate::render::RenderError;
13use crate::scale::ScaleSet;
14use crate::stat::xdensity_ridges::StatXDensityRidges;
15use crate::stat::Stat;
16use crate::theme::Theme;
17
18use super::{Geom, GeomParams};
19
20/// Ridgeline geometry: a filled density per group of a discrete y.
21pub struct GeomDensityRidges {
22    pub fill: (u8, u8, u8),
23    pub color: (u8, u8, u8),
24    pub alpha: f64,
25    pub line_width: f64,
26    /// A ridge's peak height in rows (1.0: it just reaches the next
27    /// baseline; more: ridges overlap). Give the y scale `scale - 0.5` rows
28    /// of room above the last level
29    /// ([`ScaleDiscrete::with_expand`](crate::scale::discrete::ScaleDiscrete::with_expand))
30    /// or the top ridge is clipped.
31    pub scale: f64,
32}
33
34impl Default for GeomDensityRidges {
35    fn default() -> Self {
36        GeomDensityRidges {
37            fill: (97, 156, 255),
38            color: (255, 255, 255),
39            alpha: 0.85,
40            line_width: 0.8,
41            scale: 1.6,
42        }
43    }
44}
45
46impl Geom for GeomDensityRidges {
47    fn key_fill(&self) -> Option<((u8, u8, u8), f64)> {
48        Some((self.fill, self.alpha))
49    }
50
51    fn draw(
52        &self,
53        data: &DataFrame,
54        coord: &dyn Coord,
55        scales: &ScaleSet,
56        _theme: &Theme,
57        backend: &mut dyn DrawBackend,
58    ) -> Result<(), RenderError> {
59        let x_col = data
60            .column("x")
61            .ok_or(RenderError::MissingAesthetic("x".into()))?;
62        let y_col = data
63            .column("y")
64            .ok_or(RenderError::MissingAesthetic("y".into()))?;
65        let h_col = data
66            .column("height")
67            .ok_or(RenderError::MissingAesthetic("height".into()))?;
68        let fill_col = data.column("fill");
69        let plot_area = backend.plot_area();
70        let x_scale = scales.get(&Aesthetic::X);
71        let y_scale = scales.get(&Aesthetic::Y);
72
73        // One row's height in the y scale's mapped space: the smallest gap
74        // between two neighbouring levels.
75        let mut pos: Vec<f64> = y_scale
76            .map(|s| s.breaks().iter().map(|(p, _)| *p).collect())
77            .unwrap_or_default();
78        pos.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
79        let row = pos
80            .windows(2)
81            .map(|w| (w[1] - w[0]).abs())
82            .filter(|d| *d > 0.0)
83            .fold(f64::INFINITY, f64::min);
84        let row = if row.is_finite() { row } else { 0.5 };
85
86        // The stat stacks one block of rows per group; collect them by y.
87        let mut order: Vec<String> = Vec::new();
88        let mut groups: HashMap<String, Vec<usize>> = HashMap::new();
89        for (i, yv) in y_col.iter().enumerate() {
90            let key = format!("{yv:?}");
91            groups
92                .entry(key.clone())
93                .or_insert_with(|| {
94                    order.push(key.clone());
95                    Vec::new()
96                })
97                .push(i);
98        }
99        // Back to front: the highest baseline first, so a lower ridge is
100        // drawn over the one above it.
101        let base = |idxs: &Vec<usize>| y_scale.map(|s| s.map(&y_col[idxs[0]])).unwrap_or(0.0);
102        order.sort_by(|a, b| {
103            base(&groups[b])
104                .partial_cmp(&base(&groups[a]))
105                .unwrap_or(std::cmp::Ordering::Equal)
106        });
107        for key in &order {
108            let idxs = &groups[key];
109            let first = idxs[0];
110            let ny = base(idxs);
111            let fill = fill_col
112                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first]))
113                .unwrap_or(self.fill);
114            let group = Some(super::tip_value(&y_col[first])).filter(|s| !s.is_empty());
115            super::set_mark(
116                backend,
117                group.clone(),
118                group,
119                super::series_key(data, first),
120                None,
121            );
122            let mut top: Vec<(f64, f64)> = Vec::with_capacity(idxs.len() + 2);
123            let mut x0 = f64::NAN;
124            let mut x1 = f64::NAN;
125            for &i in idxs {
126                let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
127                let h = h_col[i].as_f64().unwrap_or(0.0).max(0.0);
128                if x0.is_nan() {
129                    x0 = nx;
130                }
131                x1 = nx;
132                top.push(coord.transform((nx, ny + h * self.scale * row), &plot_area));
133            }
134            if top.len() < 2 {
135                continue;
136            }
137            let mut poly = vec![coord.transform((x0, ny), &plot_area)];
138            poly.extend(top);
139            poly.push(coord.transform((x1, ny), &plot_area));
140            backend.draw_polygon(
141                &poly,
142                &RectStyle {
143                    fill: Some(fill),
144                    stroke: Some(self.color),
145                    stroke_width: self.line_width,
146                    alpha: self.alpha,
147                    clip: true,
148                    corner_radius: 0.0,
149                },
150            )?;
151        }
152        super::clear_mark(backend);
153        Ok(())
154    }
155
156    fn required_aes(&self) -> Vec<Aesthetic> {
157        vec![Aesthetic::X, Aesthetic::Y]
158    }
159
160    fn default_stat(&self) -> Box<dyn Stat> {
161        Box::new(StatXDensityRidges::default())
162    }
163
164    fn default_position(&self) -> Box<dyn Position> {
165        Box::new(PositionIdentity)
166    }
167
168    fn default_params(&self) -> GeomParams {
169        GeomParams::default()
170    }
171
172    fn name(&self) -> &str {
173        "density_ridges"
174    }
175
176    fn set_series_color(&mut self, color: (u8, u8, u8)) {
177        self.fill = color;
178    }
179}