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            super::set_mark(
88                backend,
89                Some(tip),
90                Some(group.clone()).filter(|g| !g.is_empty()),
91                super::series_key(data, i).or(Some(group).filter(|g| !g.is_empty())),
92                super::raw_value(&Value::Float(middle)),
93            );
94
95            // Box (IQR) — honour a mapped `fill` (e.g. by group), else the default.
96            let box_fill = fill_col
97                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
98                .unwrap_or(self.fill);
99            let (box_left, box_top) = coord.transform((nx - half_width, map_y(upper)), &plot_area);
100            let (box_right, box_bottom) =
101                coord.transform((nx + half_width, map_y(lower)), &plot_area);
102            backend.draw_rect(
103                (box_left, box_top),
104                (box_right, box_bottom),
105                &RectStyle {
106                    fill: Some(box_fill),
107                    stroke: Some(self.color),
108                    stroke_width: 1.0,
109                    alpha: self.alpha,
110                    clip: true,
111                },
112            )?;
113
114            // Median line
115            let (med_left, med_y) = coord.transform((nx - half_width, map_y(middle)), &plot_area);
116            let (med_right, _) = coord.transform((nx + half_width, map_y(middle)), &plot_area);
117            backend.draw_line(
118                &[(med_left, med_y), (med_right, med_y)],
119                &LineStyle {
120                    color: self.color,
121                    width: 2.0,
122                    alpha: 1.0,
123                    linetype: Linetype::Solid,
124                },
125            )?;
126
127            // Lower whisker
128            let (_, whisker_bottom) = coord.transform((nx, map_y(ymin)), &plot_area);
129            let (center_x, _) = coord.transform((nx, map_y(lower)), &plot_area);
130            backend.draw_line(
131                &[(center_x, box_bottom), (center_x, whisker_bottom)],
132                &LineStyle {
133                    color: self.color,
134                    width: 1.0,
135                    alpha: 1.0,
136                    linetype: Linetype::Solid,
137                },
138            )?;
139            // Lower whisker cap
140            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymin)), &plot_area);
141            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymin)), &plot_area);
142            backend.draw_line(
143                &[(wl, whisker_bottom), (wr, whisker_bottom)],
144                &LineStyle {
145                    color: self.color,
146                    width: 1.0,
147                    alpha: 1.0,
148                    linetype: Linetype::Solid,
149                },
150            )?;
151
152            // Upper whisker
153            let (_, whisker_top) = coord.transform((nx, map_y(ymax)), &plot_area);
154            backend.draw_line(
155                &[(center_x, box_top), (center_x, whisker_top)],
156                &LineStyle {
157                    color: self.color,
158                    width: 1.0,
159                    alpha: 1.0,
160                    linetype: Linetype::Solid,
161                },
162            )?;
163            // Upper whisker cap
164            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymax)), &plot_area);
165            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymax)), &plot_area);
166            backend.draw_line(
167                &[(wl, whisker_top), (wr, whisker_top)],
168                &LineStyle {
169                    color: self.color,
170                    width: 1.0,
171                    alpha: 1.0,
172                    linetype: Linetype::Solid,
173                },
174            )?;
175
176            // Outliers
177            if let Some(oc) = outliers_col {
178                if let Value::Str(s) = &oc[i] {
179                    for part in s.split(',') {
180                        if let Ok(val) = part.trim().parse::<f64>() {
181                            let ny = map_y(val);
182                            let (ox, oy) = coord.transform((nx, ny), &plot_area);
183                            backend.draw_circle(
184                                (ox, oy),
185                                2.0,
186                                &PointStyle {
187                                    color: self.color,
188                                    alpha: 1.0,
189                                    filled: false,
190                                    shape: PointShape::Circle,
191                                },
192                            )?;
193                        }
194                    }
195                }
196            }
197        }
198        super::clear_mark(backend);
199
200        Ok(())
201    }
202
203    fn required_aes(&self) -> Vec<Aesthetic> {
204        vec![Aesthetic::X, Aesthetic::Y]
205    }
206
207    fn default_stat(&self) -> Box<dyn Stat> {
208        Box::new(StatBoxplot)
209    }
210
211    fn default_position(&self) -> Box<dyn Position> {
212        Box::new(PositionIdentity)
213    }
214
215    fn default_params(&self) -> GeomParams {
216        GeomParams::default()
217    }
218
219    fn name(&self) -> &str {
220        "boxplot"
221    }
222
223    fn set_series_color(&mut self, color: (u8, u8, u8)) {
224        self.fill = color;
225    }
226}