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                    ..Default::default()
125                },
126            )?;
127
128            // Lower whisker
129            let (_, whisker_bottom) = coord.transform((nx, map_y(ymin)), &plot_area);
130            let (center_x, _) = coord.transform((nx, map_y(lower)), &plot_area);
131            backend.draw_line(
132                &[(center_x, box_bottom), (center_x, whisker_bottom)],
133                &LineStyle {
134                    color: self.color,
135                    width: 1.0,
136                    alpha: 1.0,
137                    linetype: Linetype::Solid,
138                    ..Default::default()
139                },
140            )?;
141            // Lower whisker cap
142            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymin)), &plot_area);
143            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymin)), &plot_area);
144            backend.draw_line(
145                &[(wl, whisker_bottom), (wr, whisker_bottom)],
146                &LineStyle {
147                    color: self.color,
148                    width: 1.0,
149                    alpha: 1.0,
150                    linetype: Linetype::Solid,
151                    ..Default::default()
152                },
153            )?;
154
155            // Upper whisker
156            let (_, whisker_top) = coord.transform((nx, map_y(ymax)), &plot_area);
157            backend.draw_line(
158                &[(center_x, box_top), (center_x, whisker_top)],
159                &LineStyle {
160                    color: self.color,
161                    width: 1.0,
162                    alpha: 1.0,
163                    linetype: Linetype::Solid,
164                    ..Default::default()
165                },
166            )?;
167            // Upper whisker cap
168            let (wl, _) = coord.transform((nx - half_width * 0.5, map_y(ymax)), &plot_area);
169            let (wr, _) = coord.transform((nx + half_width * 0.5, map_y(ymax)), &plot_area);
170            backend.draw_line(
171                &[(wl, whisker_top), (wr, whisker_top)],
172                &LineStyle {
173                    color: self.color,
174                    width: 1.0,
175                    alpha: 1.0,
176                    linetype: Linetype::Solid,
177                    ..Default::default()
178                },
179            )?;
180
181            // Outliers
182            if let Some(oc) = outliers_col {
183                if let Value::Str(s) = &oc[i] {
184                    for part in s.split(',') {
185                        if let Ok(val) = part.trim().parse::<f64>() {
186                            let ny = map_y(val);
187                            let (ox, oy) = coord.transform((nx, ny), &plot_area);
188                            backend.draw_circle(
189                                (ox, oy),
190                                2.0,
191                                &PointStyle {
192                                    color: self.color,
193                                    alpha: 1.0,
194                                    filled: false,
195                                    shape: PointShape::Circle,
196                                },
197                            )?;
198                        }
199                    }
200                }
201            }
202        }
203        super::clear_mark(backend);
204
205        Ok(())
206    }
207
208    fn required_aes(&self) -> Vec<Aesthetic> {
209        vec![Aesthetic::X, Aesthetic::Y]
210    }
211
212    fn default_stat(&self) -> Box<dyn Stat> {
213        Box::new(StatBoxplot)
214    }
215
216    fn default_position(&self) -> Box<dyn Position> {
217        Box::new(PositionIdentity)
218    }
219
220    fn default_params(&self) -> GeomParams {
221        GeomParams::default()
222    }
223
224    fn name(&self) -> &str {
225        "boxplot"
226    }
227
228    fn set_series_color(&mut self, color: (u8, u8, u8)) {
229        self.fill = color;
230    }
231}