Skip to main content

ggplot_rs/geom/
boxplot.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::boxplot::StatBoxplot;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Boxplot geometry.
16pub struct GeomBoxplot {
17    pub fill: (u8, u8, u8),
18    pub color: (u8, u8, u8),
19    pub width: f64,
20    pub alpha: f64,
21}
22
23impl Default for GeomBoxplot {
24    fn default() -> Self {
25        GeomBoxplot {
26            fill: (255, 255, 255),
27            color: (50, 50, 50),
28            width: 0.75,
29            alpha: 1.0,
30        }
31    }
32}
33
34impl Geom for GeomBoxplot {
35    fn draw(
36        &self,
37        data: &DataFrame,
38        coord: &dyn Coord,
39        scales: &ScaleSet,
40        _theme: &Theme,
41        backend: &mut dyn DrawBackend,
42    ) -> Result<(), RenderError> {
43        let x_col = data
44            .column("x")
45            .ok_or(RenderError::MissingAesthetic("x".into()))?;
46        let lower_col = data.column("lower");
47        let middle_col = data.column("middle");
48        let upper_col = data.column("upper");
49        let ymin_col = data.column("ymin");
50        let ymax_col = data.column("ymax");
51        let outliers_col = data.column("outliers");
52        let fill_col = data.column("fill");
53
54        let plot_area = backend.plot_area();
55        let x_scale = scales.get(&Aesthetic::X);
56        let y_scale = scales.get(&Aesthetic::Y);
57
58        let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
59
60        for i in 0..data.nrows() {
61            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.5);
62
63            let half_width = if x_is_discrete {
64                let n = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
65                self.width / (n.max(1) as f64 * 2.5)
66            } else {
67                0.03
68            };
69
70            // Get boxplot values
71            let lower = lower_col.and_then(|c| c[i].as_f64()).unwrap_or(0.0);
72            let middle = middle_col.and_then(|c| c[i].as_f64()).unwrap_or(0.0);
73            let upper = upper_col.and_then(|c| c[i].as_f64()).unwrap_or(0.0);
74            let ymin = ymin_col.and_then(|c| c[i].as_f64()).unwrap_or(lower);
75            let ymax = ymax_col.and_then(|c| c[i].as_f64()).unwrap_or(upper);
76
77            let map_y = |v: f64| y_scale.map(|s| s.map(&Value::Float(v))).unwrap_or(0.0);
78
79            // Hover tooltip for the whole box: group + median (IQR).
80            let group = super::tip_value(&x_col[i]);
81            let r = |v: f64| (v * 100.0).round() / 100.0;
82            let tip = if group.is_empty() {
83                format!("median {} ({}–{})", r(middle), r(lower), r(upper))
84            } else {
85                format!("{group}: median {} ({}–{})", r(middle), r(lower), r(upper))
86            };
87            let middle_value = Value::Float(middle);
88            super::set_mark(
89                backend,
90                Some(tip),
91                Some(group.clone()).filter(|g| !g.is_empty()),
92                super::series_key(data, i).or(Some(group).filter(|g| !g.is_empty())),
93                super::raw_value(&middle_value),
94            );
95            super::set_mark_formatted(
96                backend,
97                scales,
98                Some(&x_col[i]),
99                &Aesthetic::Y,
100                Some(&middle_value),
101            );
102
103            // Box (IQR) — honour a mapped `fill` (e.g. by group), else the default.
104            let box_fill = fill_col
105                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
106                .unwrap_or(self.fill);
107            let (box_left, box_top) = coord.transform((nx - half_width, map_y(upper)), &plot_area);
108            let (box_right, box_bottom) =
109                coord.transform((nx + half_width, map_y(lower)), &plot_area);
110            backend.draw_rect(
111                (box_left, box_top),
112                (box_right, box_bottom),
113                &RectStyle {
114                    fill: Some(box_fill),
115                    stroke: Some(self.color),
116                    stroke_width: 1.0,
117                    alpha: self.alpha,
118                    clip: true,
119                },
120            )?;
121
122            // Median line
123            let (med_left, med_y) = coord.transform((nx - half_width, map_y(middle)), &plot_area);
124            let (med_right, _) = coord.transform((nx + half_width, map_y(middle)), &plot_area);
125            backend.draw_line(
126                &[(med_left, med_y), (med_right, med_y)],
127                &LineStyle {
128                    color: self.color,
129                    width: 2.0,
130                    alpha: 1.0,
131                    linetype: Linetype::Solid,
132                    ..Default::default()
133                },
134            )?;
135
136            // Lower whisker
137            let (_, whisker_bottom) = coord.transform((nx, map_y(ymin)), &plot_area);
138            let (center_x, _) = coord.transform((nx, map_y(lower)), &plot_area);
139            backend.draw_line(
140                &[(center_x, box_bottom), (center_x, whisker_bottom)],
141                &LineStyle {
142                    color: self.color,
143                    width: 1.0,
144                    alpha: 1.0,
145                    linetype: Linetype::Solid,
146                    ..Default::default()
147                },
148            )?;
149            // Lower whisker cap
150            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymin)), &plot_area);
151            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymin)), &plot_area);
152            backend.draw_line(
153                &[(wl, whisker_bottom), (wr, whisker_bottom)],
154                &LineStyle {
155                    color: self.color,
156                    width: 1.0,
157                    alpha: 1.0,
158                    linetype: Linetype::Solid,
159                    ..Default::default()
160                },
161            )?;
162
163            // Upper whisker
164            let (_, whisker_top) = coord.transform((nx, map_y(ymax)), &plot_area);
165            backend.draw_line(
166                &[(center_x, box_top), (center_x, whisker_top)],
167                &LineStyle {
168                    color: self.color,
169                    width: 1.0,
170                    alpha: 1.0,
171                    linetype: Linetype::Solid,
172                    ..Default::default()
173                },
174            )?;
175            // Upper whisker cap
176            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymax)), &plot_area);
177            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymax)), &plot_area);
178            backend.draw_line(
179                &[(wl, whisker_top), (wr, whisker_top)],
180                &LineStyle {
181                    color: self.color,
182                    width: 1.0,
183                    alpha: 1.0,
184                    linetype: Linetype::Solid,
185                    ..Default::default()
186                },
187            )?;
188
189            // Outliers
190            if let Some(oc) = outliers_col {
191                if let Value::Str(s) = &oc[i] {
192                    for part in s.split(',') {
193                        if let Ok(val) = part.trim().parse::<f64>() {
194                            let ny = map_y(val);
195                            let (ox, oy) = coord.transform((nx, ny), &plot_area);
196                            backend.draw_circle(
197                                (ox, oy),
198                                2.0,
199                                &PointStyle {
200                                    color: self.color,
201                                    alpha: 1.0,
202                                    filled: false,
203                                    shape: PointShape::Circle,
204                                },
205                            )?;
206                        }
207                    }
208                }
209            }
210        }
211        super::clear_mark(backend);
212
213        Ok(())
214    }
215
216    fn required_aes(&self) -> Vec<Aesthetic> {
217        vec![Aesthetic::X, Aesthetic::Y]
218    }
219
220    fn default_stat(&self) -> Box<dyn Stat> {
221        Box::new(StatBoxplot)
222    }
223
224    fn default_position(&self) -> Box<dyn Position> {
225        Box::new(PositionIdentity)
226    }
227
228    fn default_params(&self) -> GeomParams {
229        GeomParams::default()
230    }
231
232    fn name(&self) -> &str {
233        "boxplot"
234    }
235
236    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
237        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
238            self.color = ink;
239        }
240        if let (true, Some(paper)) = (self.fill == (255, 255, 255), el.paper) {
241            self.fill = paper;
242        }
243    }
244
245    fn set_series_color(&mut self, color: (u8, u8, u8)) {
246        self.fill = color;
247    }
248}