Skip to main content

ggplot_rs/geom/
area.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::{DataFrame, Value};
4use crate::position::stack::PositionStack;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, LineStyle, Linetype, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::align::StatAlign;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Area geometry — filled polygon from line to x-axis baseline.
16pub struct GeomArea {
17    pub fill: (u8, u8, u8),
18    pub color: (u8, u8, u8),
19    pub alpha: f64,
20    pub line_width: f64,
21    /// How consecutive points are joined (straight by default; a smooth
22    /// `areaspline` with [`Interpolate::MonotoneCubic`](super::support::Interpolate::MonotoneCubic)).
23    pub interpolate: super::support::Interpolate,
24    /// Fill each side of a threshold in its own colour (red below, green
25    /// above), cut at the exact crossing; one outline. Along y, each part
26    /// fills between the curve and the threshold.
27    pub split: Option<super::support::SignSplit>,
28}
29
30impl Default for GeomArea {
31    fn default() -> Self {
32        GeomArea {
33            fill: (97, 156, 255),
34            color: (50, 50, 50),
35            alpha: 0.4,
36            line_width: 1.0,
37            interpolate: super::support::Interpolate::Linear,
38            split: None,
39        }
40    }
41}
42
43/// Polygons, each with its fill colour.
44pub(crate) type Parts = Vec<(Vec<(f64, f64)>, (u8, u8, u8))>;
45
46/// A band (upper curve over lower, in scale space) cut by `sp`: one polygon
47/// per run, in its side's colour. Along y each run fills down (up) to the
48/// threshold; along x the band is cut at `x = at`.
49pub(crate) fn split_band(
50    sp: &super::support::SignSplit,
51    upper: &[(f64, f64)],
52    lower: &[(f64, f64)],
53    x_scale: Option<&dyn crate::scale::Scale>,
54    y_scale: Option<&dyn crate::scale::Scale>,
55) -> Parts {
56    use super::support::{split_runs, SplitAxis};
57    match sp.axis {
58        SplitAxis::Y => {
59            let at = y_scale.map_or(sp.at, |s| s.map(&Value::Float(sp.at)));
60            split_runs(upper, SplitAxis::Y, at)
61                .into_iter()
62                .filter_map(|(above, mut run)| {
63                    let (first, last) = (run.first()?.0, run.last()?.0);
64                    run.extend([(last, at), (first, at)]);
65                    Some((run, sp.colour(above)))
66                })
67                .collect()
68        }
69        SplitAxis::X => {
70            let at = x_scale.map_or(sp.at, |s| s.map(&Value::Float(sp.at)));
71            let lows = split_runs(lower, SplitAxis::X, at);
72            split_runs(upper, SplitAxis::X, at)
73                .into_iter()
74                .zip(lows)
75                .map(|((above, mut up), (_, low))| {
76                    up.extend(low.into_iter().rev());
77                    (up, sp.colour(above))
78                })
79                .collect()
80        }
81    }
82}
83
84impl Geom for GeomArea {
85    fn key_fill(&self) -> Option<((u8, u8, u8), f64)> {
86        Some((self.fill, self.alpha))
87    }
88
89    fn draw(
90        &self,
91        data: &DataFrame,
92        coord: &dyn Coord,
93        scales: &ScaleSet,
94        _theme: &Theme,
95        backend: &mut dyn DrawBackend,
96    ) -> Result<(), RenderError> {
97        let x_col = data
98            .column("x")
99            .ok_or(RenderError::MissingAesthetic("x".into()))?;
100        let y_col = data
101            .column("y")
102            .ok_or(RenderError::MissingAesthetic("y".into()))?;
103
104        // A fill/color aesthetic (or an explicit group) splits the data into one
105        // filled band per series — as in a grouped or stacked area chart.
106        let group_col = data
107            .column("fill")
108            .or_else(|| data.column("color"))
109            .or_else(|| data.column("group"));
110        // `ymin` is set by position="stack"/"fill" (the bottom of each segment);
111        // without it the band runs from the y=0 baseline.
112        let ymin_col = data.column("ymin");
113
114        let plot_area = backend.plot_area();
115        let x_scale = scales.get(&Aesthetic::X);
116        let y_scale = scales.get(&Aesthetic::Y);
117        let base_ny = y_scale.map(|s| s.map(&Value::Float(0.0))).unwrap_or(0.0);
118
119        // Group row indices by the series key, preserving first-seen order (which
120        // is the stacking order the position adjustment produced).
121        let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
122        match group_col {
123            Some(gc) => {
124                for (i, v) in gc.iter().enumerate() {
125                    let key = v.to_group_key();
126                    match groups.iter_mut().find(|(k, _)| k == &key) {
127                        Some((_, idx)) => idx.push(i),
128                        None => groups.push((key, vec![i])),
129                    }
130                }
131            }
132            None => groups.push((String::new(), (0..data.nrows()).collect())),
133        }
134
135        for (_, indices) in &groups {
136            // Order this series left-to-right so the band is a clean polygon.
137            let mut idx = indices.clone();
138            idx.sort_by(|&a, &b| {
139                let xa = x_scale.map(|s| s.map(&x_col[a])).unwrap_or(0.0);
140                let xb = x_scale.map(|s| s.map(&x_col[b])).unwrap_or(0.0);
141                xa.total_cmp(&xb)
142            });
143
144            let fill = group_col
145                .and_then(|gc| scales.map_color(&Aesthetic::Fill, &gc[idx[0]]))
146                .or_else(|| {
147                    group_col.and_then(|gc| scales.map_color(&Aesthetic::Color, &gc[idx[0]]))
148                })
149                .unwrap_or(self.fill);
150
151            let mut upper_raw: Vec<(f64, f64)> = Vec::with_capacity(idx.len());
152            let mut lower_raw: Vec<(f64, f64)> = Vec::with_capacity(idx.len());
153            for &i in &idx {
154                let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
155                let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
156                let nb = ymin_col
157                    .and_then(|c| c[i].as_f64())
158                    .and_then(|v| y_scale.map(|s| s.map(&Value::Float(v))))
159                    .unwrap_or(base_ny);
160                upper_raw.push((nx, ny));
161                lower_raw.push((nx, nb));
162            }
163            let smooth = |pts: &[(f64, f64)]| super::support::interpolate(pts, self.interpolate).0;
164            let px = |pts: &[(f64, f64)]| -> Vec<(f64, f64)> {
165                pts.iter()
166                    .map(|&p| coord.transform(p, &plot_area))
167                    .collect()
168            };
169            let (up_n, low_n) = (smooth(&upper_raw), smooth(&lower_raw));
170            let upper = px(&up_n);
171            // the filled parts: the whole band, or one per side of the split
172            let parts = match &self.split {
173                None => {
174                    let mut poly = up_n.clone();
175                    poly.extend(low_n.iter().rev());
176                    vec![(poly, fill)]
177                }
178                Some(sp) => split_band(sp, &up_n, &low_n, x_scale, y_scale),
179            };
180            for (poly, colour) in parts {
181                if poly.len() >= 3 {
182                    backend.draw_polygon(
183                        &px(&poly),
184                        &RectStyle {
185                            fill: Some(colour),
186                            stroke: None,
187                            stroke_width: 0.0,
188                            alpha: self.alpha,
189                            clip: true,
190                            corner_radius: 0.0,
191                        },
192                    )?;
193                }
194            }
195            if upper.len() >= 2 {
196                // A single-series area keeps its dark outline; multi-series bands
197                // outline in their own fill so stacked bands stay legible.
198                let line_color = if groups.len() > 1 { fill } else { self.color };
199                backend.draw_line(
200                    &upper,
201                    &LineStyle {
202                        color: line_color,
203                        alpha: 1.0,
204                        width: self.line_width,
205                        linetype: Linetype::Solid,
206                        ..Default::default()
207                    },
208                )?;
209            }
210        }
211
212        Ok(())
213    }
214
215    fn required_aes(&self) -> Vec<Aesthetic> {
216        vec![Aesthetic::X, Aesthetic::Y]
217    }
218
219    fn default_stat(&self) -> Box<dyn Stat> {
220        // ggplot2 parity (#172): `geom_area()`'s default stat is
221        // `stat_align()`, so series sampled at different x stack without
222        // dipping where one has no row.
223        Box::new(StatAlign)
224    }
225    fn default_position(&self) -> Box<dyn Position> {
226        // ggplot2 parity (sipemu/ggplot-rs#171 review finding 5): `geom_area()`
227        // defaults to `position_stack()`, same as `geom_col()`/`geom_bar()`
228        // (#169, just above those geoms' own `default_position`). 0.23/0.24
229        // left this as `PositionIdentity`, the same gap #169 fixed for
230        // `geom_col()` — landing it in the same minor as #169 so every
231        // default-position parity break is in one release.
232        Box::new(PositionStack)
233    }
234    fn default_params(&self) -> GeomParams {
235        GeomParams::default()
236    }
237    fn name(&self) -> &str {
238        "area"
239    }
240
241    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
242        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
243            self.color = ink;
244        }
245    }
246
247    fn include_zero_baseline(&self) -> bool {
248        true
249    }
250
251    fn set_series_color(&mut self, color: (u8, u8, u8)) {
252        self.fill = color;
253    }
254}