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