Skip to main content

tui_chart/
boxplot.rs

1//! BoxPlot: box-and-whisker chart from raw samples or precomputed statistics.
2
3use crate::text::{put_str, trunc};
4use crate::theme::{self, Theme};
5use crate::util::nice_ticks;
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// Direction of the value axis.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum BoxOrientation {
17    /// Values run bottom to top, groups left to right.
18    #[default]
19    Vertical,
20    /// Values run left to right, groups top to bottom.
21    Horizontal,
22}
23
24/// Five-number summary plus outliers.
25#[derive(Debug, Clone, PartialEq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct BoxStats {
28    /// Lower whisker end.
29    pub min: f64,
30    /// First quartile.
31    pub q1: f64,
32    /// Median.
33    pub median: f64,
34    /// Third quartile.
35    pub q3: f64,
36    /// Upper whisker end.
37    pub max: f64,
38    /// Points outside the whiskers.
39    pub outliers: Vec<f64>,
40}
41
42impl BoxStats {
43    /// Precomputed statistics (no outliers).
44    pub fn new(min: f64, q1: f64, median: f64, q3: f64, max: f64) -> Self {
45        Self {
46            min,
47            q1,
48            median,
49            q3,
50            max,
51            outliers: vec![],
52        }
53    }
54
55    /// Add outliers.
56    pub fn outliers(mut self, o: impl IntoIterator<Item = f64>) -> Self {
57        self.outliers = o.into_iter().filter(|v| v.is_finite()).collect();
58        self
59    }
60
61    /// Compute from samples with whiskers at `k` × IQR (non-finite values ignored).
62    /// Returns `None` when there are no finite samples.
63    pub fn from_samples(samples: &[f64], k: f64) -> Option<Self> {
64        let mut s: Vec<f64> = samples.iter().copied().filter(|v| v.is_finite()).collect();
65        if s.is_empty() {
66            return None;
67        }
68        s.sort_by(|a, b| a.total_cmp(b));
69        let q = |p: f64| {
70            let pos = p * (s.len() - 1) as f64;
71            let (lo, hi) = (pos.floor() as usize, pos.ceil() as usize);
72            s[lo] + (s[hi] - s[lo]) * (pos - lo as f64)
73        };
74        let (q1, med, q3) = (q(0.25), q(0.5), q(0.75));
75        let k = if k.is_finite() && k >= 0.0 { k } else { 1.5 };
76        let iqr = q3 - q1;
77        let (lo_f, hi_f) = (q1 - k * iqr, q3 + k * iqr);
78        let mut inside = s.iter().filter(|v| **v >= lo_f && **v <= hi_f);
79        let min = inside.clone().next().copied().unwrap_or(q1);
80        let max = inside.next_back().copied().unwrap_or(q3);
81        let outliers = s
82            .iter()
83            .copied()
84            .filter(|v| *v < lo_f || *v > hi_f)
85            .collect();
86        Some(Self {
87            min,
88            q1,
89            median: med,
90            q3,
91            max,
92            outliers,
93        })
94    }
95
96    fn valid(&self) -> bool {
97        [self.min, self.q1, self.median, self.q3, self.max]
98            .iter()
99            .all(|v| v.is_finite())
100    }
101}
102
103#[derive(Debug, Clone)]
104struct Group {
105    label: String,
106    stats: Option<BoxStats>,
107}
108
109/// Box-and-whisker chart widget.
110#[derive(Debug, Clone)]
111pub struct BoxPlot {
112    groups: Vec<Group>,
113    colors: Option<Vec<Color>>,
114    theme: Option<Theme>,
115    base: Option<Style>,
116    orientation: BoxOrientation,
117    whisker_iqr: f64,
118    show_outliers: bool,
119    range: Option<(f64, f64)>,
120    block: Option<Block<'static>>,
121}
122
123impl Default for BoxPlot {
124    fn default() -> Self {
125        Self::new()
126    }
127}
128
129impl BoxPlot {
130    /// Empty chart.
131    pub fn new() -> Self {
132        Self {
133            groups: vec![],
134            colors: None,
135            theme: None,
136            base: None,
137            orientation: BoxOrientation::Vertical,
138            whisker_iqr: 1.5,
139            show_outliers: true,
140            range: None,
141            block: None,
142        }
143    }
144
145    /// Add a group computed from raw samples (uses the current whisker factor,
146    /// so call [`BoxPlot::whisker_iqr`] first if you change it).
147    pub fn group(
148        mut self,
149        label: impl Into<String>,
150        samples: impl IntoIterator<Item = f64>,
151    ) -> Self {
152        let v: Vec<f64> = samples.into_iter().collect();
153        self.groups.push(Group {
154            label: label.into(),
155            stats: BoxStats::from_samples(&v, self.whisker_iqr),
156        });
157        self
158    }
159
160    /// Add a group from precomputed statistics.
161    pub fn stats(mut self, label: impl Into<String>, stats: BoxStats) -> Self {
162        self.groups.push(Group {
163            label: label.into(),
164            stats: Some(stats),
165        });
166        self
167    }
168
169    setter!(
170        /// Whisker length as a multiple of the IQR (default 1.5).
171        whisker_iqr: f64
172    );
173
174    /// Per-group colors (cycled).
175    pub fn colors(mut self, c: Vec<Color>) -> Self {
176        if !c.is_empty() {
177            self.colors = Some(c);
178        }
179        self
180    }
181
182    theme_setter!(
183        /// Apply a [`Theme`]: palette group colors, outlier (bear) color, axis
184        /// colors and background fill. Explicit [`BoxPlot::colors`] win.
185        theme
186    );
187
188    base_style_setter!(base);
189
190    fn group_color(&self, i: usize) -> Color {
191        if let Some(c) = &self.colors {
192            return c[i % c.len()];
193        }
194        match &self.theme {
195            Some(t) => t.color(i),
196            None => [
197                Color::Cyan,
198                Color::Magenta,
199                Color::Yellow,
200                Color::Green,
201                Color::LightRed,
202                Color::LightBlue,
203            ][i % 6],
204        }
205    }
206
207    setter!(
208        /// Orientation.
209        orientation: BoxOrientation
210    );
211
212    setter!(
213        /// Draw outliers (default on).
214        show_outliers: bool
215    );
216
217    /// Fixed value range.
218    pub fn range(mut self, min: f64, max: f64) -> Self {
219        self.range = Some((min, max));
220        self
221    }
222
223    block_setter!(block, 'static);
224
225    fn value_range(&self) -> (f64, f64) {
226        if let Some((a, b)) = self.range {
227            if a.is_finite() && b.is_finite() && b > a {
228                return (a, b);
229            }
230        }
231        let mut lo = f64::INFINITY;
232        let mut hi = f64::NEG_INFINITY;
233        for s in self
234            .groups
235            .iter()
236            .filter_map(|g| g.stats.as_ref())
237            .filter(|s| s.valid())
238        {
239            lo = lo.min(s.min);
240            hi = hi.max(s.max);
241            if self.show_outliers {
242                for &o in &s.outliers {
243                    lo = lo.min(o);
244                    hi = hi.max(o);
245                }
246            }
247        }
248        if !lo.is_finite() {
249            return (0.0, 1.0);
250        }
251        if hi <= lo {
252            return (lo - 1.0, hi + 1.0);
253        }
254        let pad = (hi - lo) * 0.05;
255        (lo - pad, hi + pad)
256    }
257}
258
259impl BoxPlot {
260    fn render_into(&self, area: Rect, buf: &mut Buffer) {
261        let area = area.intersection(buf.area);
262        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
263        if inner.width < 4 || inner.height < 3 || self.groups.is_empty() {
264            return;
265        }
266        let vert = self.orientation == BoxOrientation::Vertical;
267        let (lo, hi) = self.value_range();
268        let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
269        let text = self
270            .theme
271            .as_ref()
272            .map_or(Style::default(), |t| t.label_style());
273        let ticks = |len: u16| nice_ticks(lo, hi, (len as usize / 4).max(2));
274        let step = |t: &[f64]| if t.len() >= 2 { t[1] - t[0] } else { 1.0 };
275
276        // Layout: gutter (left) and footer (bottom) are label areas.
277        let (gutter, plot);
278        if vert {
279            let t = ticks(inner.height);
280            let w = t
281                .iter()
282                .map(|v| crate::util::format_tick(*v, step(&t)).chars().count())
283                .max()
284                .unwrap_or(1) as u16;
285            gutter = (w + 1).min(inner.width / 2);
286            plot = Rect::new(
287                inner.x + gutter,
288                inner.y,
289                inner.width - gutter,
290                inner.height - 1,
291            );
292        } else {
293            let w = self
294                .groups
295                .iter()
296                .map(|g| g.label.chars().count())
297                .max()
298                .unwrap_or(0) as u16;
299            gutter = (w + 1).min(inner.width / 3);
300            plot = Rect::new(
301                inner.x + gutter,
302                inner.y,
303                inner.width - gutter,
304                inner.height - 1,
305            );
306        }
307        if plot.width == 0 || plot.height == 0 {
308            return;
309        }
310        let (along_len, cross_len) = if vert {
311            (plot.height, plot.width)
312        } else {
313            (plot.width, plot.height)
314        };
315        let to_a = |v: f64| -> i32 {
316            let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
317            (f * (along_len - 1) as f64).round() as i32
318        };
319        let cell = |a: i32, c: i32| -> Option<(u16, u16)> {
320            if a < 0 || c < 0 || a >= along_len as i32 || c >= cross_len as i32 {
321                return None;
322            }
323            Some(if vert {
324                (plot.x + c as u16, plot.y + plot.height - 1 - a as u16)
325            } else {
326                (plot.x + a as u16, plot.y + c as u16)
327            })
328        };
329        let put = |buf: &mut Buffer, a: i32, c: i32, ch: char, st: Style| {
330            if let Some((x, y)) = cell(a, c) {
331                buf[(x, y)].set_char(ch).set_style(st);
332            }
333        };
334
335        // Value axis labels + faint grid.
336        let t = ticks(along_len);
337        let st = step(&t);
338        for v in &t {
339            let a = to_a(*v);
340            let label = crate::util::format_tick(*v, st);
341            if vert {
342                if let Some((_, y)) = cell(a, 0) {
343                    let lw = label.chars().count() as u16;
344                    put_str(
345                        buf,
346                        inner.x + gutter.saturating_sub(lw + 1),
347                        y,
348                        plot.x,
349                        &label,
350                        dim,
351                    );
352                }
353            } else if let Some((x, _)) = cell(a, 0) {
354                put_str(buf, x, inner.bottom() - 1, inner.right(), &label, dim);
355            }
356            for c in 0..cross_len as i32 {
357                if let Some((x, y)) = cell(a, c) {
358                    if buf[(x, y)].symbol() == " " {
359                        buf[(x, y)].set_char('·').set_style(dim);
360                    }
361                }
362            }
363        }
364
365        // Groups.
366        let n = self.groups.len();
367        let slot = (cross_len as f64 / n as f64).max(0.0);
368        for (i, g) in self.groups.iter().enumerate() {
369            let c0 = (i as f64 * slot).floor() as i32;
370            let c1 = (((i + 1) as f64 * slot).floor() as i32).max(c0 + 1);
371            let span = c1 - c0;
372            let bw = if span >= 5 { span - 2 } else { span.max(1) };
373            let bw = if vert { bw.min(15) } else { bw.min(5) };
374            let left = c0 + (span - bw) / 2;
375            let mid = left + bw / 2;
376            let color = self.group_color(i);
377            let s = Style::default().fg(color);
378
379            // label
380            if vert {
381                let w = span.max(0) as usize;
382                let l = trunc(&g.label, w);
383                let off = (w.saturating_sub(l.chars().count()) / 2) as u16;
384                put_str(
385                    buf,
386                    plot.x + c0 as u16 + off,
387                    inner.bottom() - 1,
388                    inner.right(),
389                    &l,
390                    text,
391                );
392            } else if let Some((_, y)) = cell(0, mid) {
393                put_str(
394                    buf,
395                    inner.x,
396                    y,
397                    plot.x,
398                    &trunc(&g.label, gutter.saturating_sub(1) as usize),
399                    text,
400                );
401            }
402
403            let Some(st) = g.stats.as_ref().filter(|s| s.valid()) else {
404                continue;
405            };
406            let (amin, aq1, amed, aq3, amax) = (
407                to_a(st.min),
408                to_a(st.q1),
409                to_a(st.median),
410                to_a(st.q3),
411                to_a(st.max),
412            );
413            let (wl, cp, ml) = if vert {
414                ('│', '─', '━')
415            } else {
416                ('─', '│', '┃')
417            };
418            for a in amin..aq1 {
419                put(buf, a, mid, wl, s);
420            }
421            for a in aq3 + 1..=amax {
422                put(buf, a, mid, wl, s);
423            }
424            let cw = (bw / 2).max(0);
425            for c in mid - cw / 2..=mid + cw / 2 {
426                put(buf, amin, c, cp, s);
427                put(buf, amax, c, cp, s);
428            }
429            for a in aq1..=aq3 {
430                for c in left..left + bw {
431                    put(buf, a, c, '█', s);
432                }
433            }
434            let ms = Style::default()
435                .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
436                .bg(color);
437            for c in left..left + bw {
438                put(buf, amed, c, ml, ms);
439            }
440            if self.show_outliers {
441                for &o in &st.outliers {
442                    let os = match (&self.colors, &self.theme) {
443                        (None, Some(t)) => Style::default().fg(t.bear),
444                        _ => s,
445                    };
446                    put(buf, to_a(o), mid, '○', os);
447                }
448            }
449        }
450    }
451}
452
453widget_impls!(BoxPlot);
454
455#[cfg(feature = "theme")]
456impl tui_nuances::Themed for BoxPlot {
457    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
458        self.theme(theme)
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use ratatui::widgets::Widget;
466
467    fn render(p: &BoxPlot, w: u16, h: u16) -> Buffer {
468        let area = Rect::new(0, 0, w, h);
469        let mut buf = Buffer::empty(area);
470        p.render(area, &mut buf);
471        buf
472    }
473
474    fn count(buf: &Buffer, sym: &str) -> usize {
475        buf.content().iter().filter(|c| c.symbol() == sym).count()
476    }
477
478    #[test]
479    fn quartiles_and_outlier() {
480        let mut v: Vec<f64> = (1..=9).map(|x| x as f64).collect();
481        v.push(100.0);
482        let s = BoxStats::from_samples(&v, 1.5).unwrap();
483        assert_eq!(s.median, 5.5);
484        assert_eq!(s.q1, 3.25);
485        assert_eq!(s.q3, 7.75);
486        assert_eq!(s.max, 9.0);
487        assert_eq!(s.outliers, vec![100.0]);
488    }
489
490    #[test]
491    fn empty_and_nan() {
492        assert!(BoxStats::from_samples(&[], 1.5).is_none());
493        assert!(BoxStats::from_samples(&[f64::NAN], 1.5).is_none());
494    }
495
496    #[test]
497    fn draws_box_median_outlier() {
498        let p = BoxPlot::new().group("a", (1..=9).map(|x| x as f64).chain([100.0]));
499        let b = render(&p, 30, 15);
500        let p2 = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
501        assert!(count(&render(&p2, 30, 15), "█") > 0);
502        assert!(count(&b, "━") > 0);
503        assert_eq!(count(&b, "○"), 1);
504    }
505
506    #[test]
507    fn horizontal_and_multi() {
508        let p = BoxPlot::new()
509            .stats("x", BoxStats::new(0.0, 2.0, 3.0, 4.0, 6.0))
510            .stats("y", BoxStats::new(1.0, 3.0, 5.0, 7.0, 9.0))
511            .orientation(BoxOrientation::Horizontal);
512        let b = render(&p, 40, 12);
513        assert!(count(&b, "┃") > 0);
514    }
515
516    #[cfg(feature = "theme")]
517    #[test]
518    fn theme_colors_and_override() {
519        let t = Theme::nord();
520        let p = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
521        let b = render(&p.clone().theme(&t), 30, 15);
522        assert!(b
523            .content()
524            .iter()
525            .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
526        assert_eq!(b[(0, 0)].bg, t.background.unwrap());
527        let b = render(&p.theme(&t).colors(vec![Color::Red]), 30, 15);
528        assert!(b
529            .content()
530            .iter()
531            .any(|c| c.symbol() == "█" && c.fg == Color::Red));
532        assert!(!b
533            .content()
534            .iter()
535            .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
536    }
537
538    #[test]
539    fn tiny_areas_no_panic() {
540        let p = BoxPlot::new()
541            .group("a", [1.0, f64::NAN, 3.0])
542            .stats("n", BoxStats::new(f64::NAN, 0.0, 0.0, 0.0, 0.0))
543            .block(Block::bordered());
544        for w in 0..8 {
545            for h in 0..6 {
546                render(&p, w, h);
547            }
548        }
549        render(&BoxPlot::new(), 10, 5);
550    }
551}