Skip to main content

ggplot_rs/geom/
density.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::density::StatDensity;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Density curve geometry — filled area under a kernel density estimate.
16pub struct GeomDensity {
17    pub fill: (u8, u8, u8),
18    pub color: (u8, u8, u8),
19    pub alpha: f64,
20    pub line_width: f64,
21    /// Fill each side of a threshold in its own colour (a distribution of
22    /// outcomes: losses red, gains green), cut at the exact crossing; one
23    /// outline. Along x by default use [`SplitAxis::X`](super::support::SplitAxis::X).
24    pub split: Option<super::support::SignSplit>,
25}
26
27impl Default for GeomDensity {
28    fn default() -> Self {
29        GeomDensity {
30            fill: (97, 156, 255),
31            color: (50, 50, 50),
32            alpha: 0.3,
33            line_width: 1.0,
34            split: None,
35        }
36    }
37}
38
39impl Geom for GeomDensity {
40    fn key_fill(&self) -> Option<((u8, u8, u8), f64)> {
41        Some((self.fill, self.alpha))
42    }
43
44    fn draw(
45        &self,
46        data: &DataFrame,
47        coord: &dyn Coord,
48        scales: &ScaleSet,
49        _theme: &Theme,
50        backend: &mut dyn DrawBackend,
51    ) -> Result<(), RenderError> {
52        let x_col = data
53            .column("x")
54            .ok_or(RenderError::MissingAesthetic("x".into()))?;
55        let y_col = data
56            .column("y")
57            .ok_or(RenderError::MissingAesthetic("y".into()))?;
58        let fill_col = data.column("fill");
59        let color_col = data.column("color");
60
61        let plot_area = backend.plot_area();
62        let x_scale = scales.get(&Aesthetic::X);
63        let y_scale = scales.get(&Aesthetic::Y);
64
65        let base_ny = y_scale.map(|s| s.map(&Value::Float(0.0))).unwrap_or(0.0);
66
67        // Determine groups from color or fill column
68        let group_col = color_col.or(fill_col);
69        let groups: Vec<(String, Vec<usize>)> = if let Some(gc) = group_col {
70            let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
71            for (i, v) in gc.iter().enumerate() {
72                let key = v.to_group_key();
73                if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
74                    entry.1.push(i);
75                } else {
76                    groups.push((key, vec![i]));
77                }
78            }
79            groups
80        } else {
81            // Single group with all indices
82            vec![("".to_string(), (0..data.nrows()).collect())]
83        };
84
85        for (group_label, indices) in &groups {
86            if indices.is_empty() {
87                continue;
88            }
89            let first_idx = indices[0];
90
91            // Resolve fill: use fill scale if fill column exists, else use color scale, else default
92            let fill_color = fill_col
93                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first_idx]))
94                .or_else(|| {
95                    color_col.and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
96                })
97                .unwrap_or(self.fill);
98
99            // Resolve line: use color scale if color column exists, else use fill scale, else default
100            let line_color = color_col
101                .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
102                .or_else(|| {
103                    fill_col.and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first_idx]))
104                })
105                .unwrap_or(self.color);
106
107            let mut up_n: Vec<(f64, f64)> = Vec::new();
108            let mut low_n: Vec<(f64, f64)> = Vec::new();
109            for &i in indices {
110                let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
111                let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
112                up_n.push((nx, ny));
113                low_n.push((nx, base_ny));
114            }
115            let px = |pts: &[(f64, f64)]| -> Vec<(f64, f64)> {
116                pts.iter()
117                    .map(|&p| coord.transform(p, &plot_area))
118                    .collect()
119            };
120            let upper = px(&up_n);
121
122            // the filled parts: the whole curve, or one per side of the split
123            let parts = match &self.split {
124                None => {
125                    let mut poly = up_n.clone();
126                    poly.extend(low_n.iter().rev());
127                    vec![(poly, fill_color)]
128                }
129                Some(sp) => super::area::split_band(sp, &up_n, &low_n, x_scale, y_scale),
130            };
131            for (poly, colour) in parts {
132                if poly.len() >= 3 {
133                    backend.draw_polygon(
134                        &px(&poly),
135                        &RectStyle {
136                            fill: Some(colour),
137                            stroke: None,
138                            stroke_width: 0.0,
139                            alpha: self.alpha,
140                            clip: true,
141                            corner_radius: 0.0,
142                        },
143                    )?;
144                }
145            }
146
147            // Top line
148            if upper.len() >= 2 {
149                backend.draw_line(
150                    &upper,
151                    &LineStyle {
152                        color: line_color,
153                        alpha: 1.0,
154                        width: self.line_width,
155                        linetype: Linetype::Solid,
156                        ..Default::default()
157                    },
158                )?;
159            }
160
161            // Sparse invisible hover points: the curve carries no marks, so emit a
162            // handful of transparent points along it (tagged with the x value and
163            // density) for the axis-pointer to read on hover.
164            let step = (indices.len() / 48).max(1);
165            for (k, &i) in indices.iter().enumerate() {
166                if k % step != 0 {
167                    continue;
168                }
169                let dens = y_col[i]
170                    .as_f64()
171                    .map(|f| format!("{f:.4}"))
172                    .unwrap_or_default();
173                let tip = if group_label.is_empty() {
174                    format!("density: {dens}")
175                } else {
176                    format!("{group_label}: {dens}")
177                };
178                super::set_mark(
179                    backend,
180                    Some(tip),
181                    Some(super::tip_value(&x_col[i])),
182                    super::series_key(data, i),
183                    super::measured_value(data, i),
184                );
185                super::set_mark_formatted(
186                    backend,
187                    scales,
188                    Some(&x_col[i]),
189                    &Aesthetic::Y,
190                    super::measured_raw(data, i),
191                );
192                backend.draw_shape(
193                    upper[k],
194                    0.6,
195                    &PointStyle {
196                        color: line_color,
197                        alpha: 0.0,
198                        filled: true,
199                        shape: PointShape::Circle,
200                    },
201                )?;
202            }
203            super::clear_mark(backend);
204        }
205
206        Ok(())
207    }
208
209    fn required_aes(&self) -> Vec<Aesthetic> {
210        vec![Aesthetic::X]
211    }
212
213    fn default_stat(&self) -> Box<dyn Stat> {
214        Box::new(StatDensity::default())
215    }
216
217    fn default_position(&self) -> Box<dyn Position> {
218        Box::new(PositionIdentity)
219    }
220
221    fn default_params(&self) -> GeomParams {
222        GeomParams::default()
223    }
224
225    fn name(&self) -> &str {
226        "density"
227    }
228
229    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
230        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
231            self.color = ink;
232        }
233    }
234
235    fn set_series_color(&mut self, color: (u8, u8, u8)) {
236        self.fill = color;
237    }
238}