Skip to main content

ggplot_rs/stat/
pareto.rs

1//! `StatPareto`: sum `y` per category, sort descending and accumulate — the
2//! data behind a Pareto chart's bars and cumulative-percentage line.
3
4use crate::aes::Aesthetic;
5use crate::data::{DataFrame, Value};
6use crate::scale::ScaleSet;
7
8use super::Stat;
9
10/// Pareto stat behind [`GeomPareto`](crate::geom::pareto::GeomPareto).
11///
12/// Output columns, one row per distinct x (largest first when `sort`):
13/// `x`, `y` (the category's summed value), `cum` (running total), `cum_pct`
14/// (running share of the grand total, 0–100), `ymin` (0) and `ymax`
15/// (= `cum`, so the y scale trains up to the grand total).
16#[derive(Clone, Debug)]
17pub struct StatPareto {
18    /// Order categories by descending value (ties keep data order). With
19    /// `false` the data order is kept.
20    pub sort: bool,
21    /// The grand total the running share is of (a top N of a longer list:
22    /// the line ends at the top N's share, not 100 %); `None` is the sum
23    /// of the rows. The y scale trains up to it.
24    pub total: Option<f64>,
25}
26
27impl Default for StatPareto {
28    fn default() -> Self {
29        StatPareto {
30            sort: true,
31            total: None,
32        }
33    }
34}
35
36impl Stat for StatPareto {
37    fn compute_group(&self, data: &DataFrame, _scales: &ScaleSet) -> DataFrame {
38        let (Some(x_col), Some(y_col)) = (data.column("x"), data.column("y")) else {
39            return DataFrame::new();
40        };
41        let mut cats: indexmap::IndexMap<String, (Value, f64)> = indexmap::IndexMap::new();
42        for (x, y) in x_col.iter().zip(y_col) {
43            let Some(v) = y.as_f64().filter(|v| v.is_finite()) else {
44                continue;
45            };
46            cats.entry(x.key_str().into_owned())
47                .or_insert_with(|| (x.clone(), 0.0))
48                .1 += v;
49        }
50        let mut rows: Vec<(Value, f64)> = cats.into_values().collect();
51        if self.sort {
52            rows.sort_by(|a, b| b.1.total_cmp(&a.1));
53        }
54        let sum: f64 = rows.iter().map(|r| r.1).sum();
55        let total = self
56            .total
57            .filter(|t| t.is_finite() && *t > 0.0)
58            .unwrap_or(sum);
59        let mut cum = 0.0;
60        let (mut xs, mut ys, mut cums, mut pcts) = (vec![], vec![], vec![], vec![]);
61        for (x, v) in rows {
62            cum += v;
63            xs.push(x);
64            ys.push(Value::Float(v));
65            cums.push(Value::Float(cum));
66            pcts.push(if total != 0.0 {
67                Value::Float(cum / total * 100.0)
68            } else {
69                Value::Na
70            });
71        }
72        let n = xs.len();
73        let mut out = DataFrame::new();
74        out.add_column("x".into(), xs);
75        out.add_column("y".into(), ys);
76        out.add_column("cum".into(), cums.clone());
77        out.add_column("cum_pct".into(), pcts);
78        out.add_column("ymin".into(), vec![Value::Float(0.0); n]);
79        // with a grand total beyond the rows, the scale reaches it (the
80        // secondary axis's 100 %)
81        let ymax = if total > sum {
82            vec![Value::Float(total); n]
83        } else {
84            cums
85        };
86        out.add_column("ymax".into(), ymax);
87        out
88    }
89
90    fn required_aes(&self) -> Vec<Aesthetic> {
91        vec![Aesthetic::X, Aesthetic::Y]
92    }
93
94    /// The ranking and running total span every category of the panel.
95    fn panelwise(&self) -> bool {
96        true
97    }
98
99    fn name(&self) -> &str {
100        "pareto"
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn sums_sorts_and_accumulates() {
110        let mut d = DataFrame::new();
111        d.add_column(
112            "x".into(),
113            ["a", "b", "c", "b"]
114                .iter()
115                .map(|s| Value::Str(s.to_string()))
116                .collect(),
117        );
118        d.add_column(
119            "y".into(),
120            [10.0, 20.0, 50.0, 20.0]
121                .iter()
122                .map(|v| Value::Float(*v))
123                .collect(),
124        );
125        let out = StatPareto::default().compute_group(&d, &ScaleSet::new());
126        let keys: Vec<String> = out
127            .column("x")
128            .unwrap()
129            .iter()
130            .map(|v| v.key_str().into_owned())
131            .collect();
132        assert_eq!(keys, ["c", "b", "a"]);
133        let f = |c: &str| -> Vec<f64> {
134            out.column(c)
135                .unwrap()
136                .iter()
137                .map(|v| v.as_f64().unwrap())
138                .collect()
139        };
140        assert_eq!(f("y"), vec![50.0, 40.0, 10.0]);
141        assert_eq!(f("cum"), vec![50.0, 90.0, 100.0]);
142        assert_eq!(f("cum_pct"), vec![50.0, 90.0, 100.0]);
143        // a top N of a longer list: the share of the grand total, and the
144        // scale reaches it
145        let out = StatPareto {
146            total: Some(400.0),
147            ..StatPareto::default()
148        }
149        .compute_group(&d, &ScaleSet::new());
150        let f = |c: &str| -> Vec<f64> {
151            out.column(c)
152                .unwrap()
153                .iter()
154                .map(|v| v.as_f64().unwrap())
155                .collect()
156        };
157        assert_eq!(f("cum_pct"), vec![12.5, 22.5, 25.0]);
158        assert_eq!(f("ymax"), vec![400.0, 400.0, 400.0]);
159    }
160}