Skip to main content

ggplot_rs/geom/
pareto.rs

1//! Pareto chart: `geom_pareto`. Categories as bars sorted by value, plus the
2//! cumulative total as a line with points, read against a 0–100 % secondary
3//! axis ([`SecAxis::percent_of_max`](crate::scale::sec_axis::SecAxis::percent_of_max)).
4
5use crate::aes::Aesthetic;
6use crate::coord::Coord;
7use crate::data::{DataFrame, Value};
8use crate::position::identity::PositionIdentity;
9use crate::position::Position;
10use crate::render::backend::{DrawBackend, LineStyle, Linetype, PointStyle, RectStyle};
11use crate::render::RenderError;
12use crate::scale::ScaleSet;
13use crate::stat::pareto::StatPareto;
14use crate::stat::Stat;
15use crate::theme::Theme;
16
17use super::{Geom, GeomParams};
18
19/// Pareto chart. Map `x` (categories) and `y` (values; repeated categories
20/// are summed). Bars are sorted descending unless `sort` is false.
21pub struct GeomPareto {
22    /// Bar fill.
23    pub fill: (u8, u8, u8),
24    /// Bar outline.
25    pub color: (u8, u8, u8),
26    /// Cumulative line and point colour.
27    pub line_color: (u8, u8, u8),
28    pub line_width: f64,
29    /// Point radius in pixels (0 hides the points).
30    pub point_size: f64,
31    /// Bar width as a fraction of the category slot.
32    pub width: f64,
33    pub alpha: f64,
34    /// Sort categories by descending value.
35    pub sort: bool,
36    /// Draw a dashed reference line at this cumulative share (e.g. `0.8`
37    /// for the 80/20 rule).
38    pub threshold: Option<f64>,
39    /// The grand total the cumulative share is of, when the bars are a top
40    /// N of a longer list ([`StatPareto::total`]); `None` is their sum.
41    pub total: Option<f64>,
42}
43
44impl Default for GeomPareto {
45    fn default() -> Self {
46        GeomPareto {
47            fill: (97, 156, 255),
48            color: (50, 50, 50),
49            line_color: (0xe8, 0x59, 0x0c),
50            line_width: 1.5,
51            point_size: 3.0,
52            width: 0.8,
53            alpha: 1.0,
54            sort: true,
55            threshold: None,
56            total: None,
57        }
58    }
59}
60
61impl GeomPareto {
62    /// Draw a dashed reference line at cumulative share `share` (0–1).
63    pub fn with_threshold(mut self, share: f64) -> Self {
64        self.threshold = Some(share);
65        self
66    }
67}
68
69impl Geom for GeomPareto {
70    fn draw(
71        &self,
72        data: &DataFrame,
73        coord: &dyn Coord,
74        scales: &ScaleSet,
75        _theme: &Theme,
76        backend: &mut dyn DrawBackend,
77    ) -> Result<(), RenderError> {
78        let col = |n: &str| {
79            data.column(n)
80                .ok_or_else(|| RenderError::MissingAesthetic(n.into()))
81        };
82        let (x_col, y_col, cum_col) = (col("x")?, col("y")?, col("cum")?);
83        let pct_col = data.column("cum_pct");
84        let area = backend.plot_area();
85        let x_scale = scales.get(&Aesthetic::X);
86        let y_scale = scales.get(&Aesthetic::Y);
87        let my = |v: f64| y_scale.map(|s| s.map(&Value::Float(v))).unwrap_or(0.0);
88        let half = if x_scale.map(|s| s.is_discrete()).unwrap_or(false) {
89            let n = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
90            let pad = if coord.discrete_expand() { 1.1 } else { 1.0 };
91            self.width / (n * pad) / 2.0
92        } else {
93            super::continuous_bar_half_width(
94                x_col.iter().filter_map(|v| x_scale.map(|s| s.map(v))),
95                self.width,
96                0.02,
97            )
98        };
99        let pct_txt = |i: usize| {
100            pct_col
101                .and_then(|c| c[i].as_f64())
102                .map(|p| {
103                    format!(
104                        "{}%",
105                        super::tip_value(&Value::Float((p * 10.0).round() / 10.0))
106                    )
107                })
108                .unwrap_or_default()
109        };
110
111        let mut line = Vec::with_capacity(data.nrows());
112        for i in 0..data.nrows() {
113            let (Some(v), Some(cum)) = (y_col[i].as_f64(), cum_col[i].as_f64()) else {
114                continue;
115            };
116            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.5);
117            let x_txt = super::tip_value(&x_col[i]);
118            super::set_mark(
119                backend,
120                Some(format!(
121                    "{x_txt}: {} (cumulative {})",
122                    super::tip_value(&y_col[i]),
123                    pct_txt(i)
124                )),
125                Some(x_txt),
126                super::series_key(data, i),
127                super::raw_value(&y_col[i]),
128            );
129            super::set_mark_formatted(
130                backend,
131                scales,
132                Some(&x_col[i]),
133                &Aesthetic::Y,
134                Some(&y_col[i]),
135            );
136            super::set_row_extras(backend, data, i);
137            let (x0, y0) = coord.transform((nx - half, my(v)), &area);
138            let (x1, y1) = coord.transform((nx + half, my(0.0)), &area);
139            backend.draw_rect(
140                (x0.min(x1), y0.min(y1)),
141                (x0.max(x1), y0.max(y1)),
142                &RectStyle {
143                    fill: Some(self.fill),
144                    stroke: Some(self.color),
145                    stroke_width: 0.5,
146                    alpha: self.alpha,
147                    clip: true,
148                    corner_radius: 0.0,
149                },
150            )?;
151            line.push((i, nx, my(cum)));
152        }
153        super::clear_row_extras(backend);
154        line.sort_by(|a, b| a.1.total_cmp(&b.1));
155
156        // the 100 % the share is of: the stat's total (cum / cum_pct)
157        let total = cum_col
158            .iter()
159            .zip(pct_col.into_iter().flatten())
160            .find_map(|(c, p)| Some(c.as_f64()? / p.as_f64().filter(|p| *p > 0.0)? * 100.0))
161            .or_else(|| cum_col.iter().filter_map(|v| v.as_f64()).reduce(f64::max));
162        if let (Some(share), Some(total)) = (self.threshold, total) {
163            super::clear_mark(backend);
164            let ny = my(share * total);
165            backend.draw_line(
166                &[
167                    coord.transform((0.0, ny), &area),
168                    coord.transform((1.0, ny), &area),
169                ],
170                &LineStyle {
171                    color: self.line_color,
172                    alpha: 0.7 * self.alpha,
173                    width: 1.0,
174                    linetype: Linetype::Dashed,
175                    ..Default::default()
176                },
177            )?;
178        }
179
180        let pts: Vec<(f64, f64)> = line
181            .iter()
182            .map(|&(_, nx, ny)| coord.transform((nx, ny), &area))
183            .collect();
184        if pts.len() > 1 {
185            super::set_mark(backend, None, None, Some("cumulative".into()), None);
186            backend.draw_line(
187                &pts,
188                &LineStyle {
189                    color: self.line_color,
190                    alpha: self.alpha,
191                    width: self.line_width,
192                    linetype: Linetype::Solid,
193                    ..Default::default()
194                },
195            )?;
196        }
197        if self.point_size > 0.0 {
198            for (&(i, _, _), &p) in line.iter().zip(&pts) {
199                let x_txt = super::tip_value(&x_col[i]);
200                super::set_mark(
201                    backend,
202                    Some(format!("{x_txt}: cumulative {}", pct_txt(i))),
203                    Some(x_txt),
204                    Some("cumulative".into()),
205                    pct_col.and_then(|c| super::raw_value(&c[i])),
206                );
207                backend.draw_circle(
208                    p,
209                    self.point_size,
210                    &PointStyle {
211                        color: self.line_color,
212                        alpha: self.alpha,
213                        filled: true,
214                        ..Default::default()
215                    },
216                )?;
217            }
218        }
219        super::clear_mark(backend);
220        Ok(())
221    }
222
223    fn required_aes(&self) -> Vec<Aesthetic> {
224        vec![Aesthetic::X, Aesthetic::Y]
225    }
226
227    fn default_stat(&self) -> Box<dyn Stat> {
228        Box::new(StatPareto {
229            sort: self.sort,
230            total: self.total,
231        })
232    }
233
234    fn default_position(&self) -> Box<dyn Position> {
235        Box::new(PositionIdentity)
236    }
237
238    fn default_params(&self) -> GeomParams {
239        GeomParams::default()
240    }
241
242    fn name(&self) -> &str {
243        "pareto"
244    }
245
246    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
247        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
248            self.color = ink;
249        }
250    }
251
252    fn consumes_tooltips(&self) -> bool {
253        true
254    }
255
256    fn include_zero_baseline(&self) -> bool {
257        true
258    }
259
260    fn set_series_color(&mut self, color: (u8, u8, u8)) {
261        self.fill = color;
262    }
263}