1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum BoxOrientation {
17 #[default]
19 Vertical,
20 Horizontal,
22}
23
24#[derive(Debug, Clone, PartialEq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct BoxStats {
28 pub min: f64,
30 pub q1: f64,
32 pub median: f64,
34 pub q3: f64,
36 pub max: f64,
38 pub outliers: Vec<f64>,
40 #[cfg_attr(feature = "serde", serde(default))]
42 pub mean: Option<f64>,
43 #[cfg_attr(feature = "serde", serde(default))]
45 pub n: usize,
46 #[cfg_attr(feature = "serde", serde(default))]
48 pub points: Vec<f64>,
49}
50
51impl BoxStats {
52 pub fn new(min: f64, q1: f64, median: f64, q3: f64, max: f64) -> Self {
54 Self {
55 min,
56 q1,
57 median,
58 q3,
59 max,
60 outliers: vec![],
61 mean: None,
62 n: 0,
63 points: vec![],
64 }
65 }
66
67 pub fn mean(mut self, m: f64) -> Self {
69 self.mean = Some(m).filter(|m| m.is_finite());
70 self
71 }
72
73 pub fn count(mut self, n: usize) -> Self {
75 self.n = n;
76 self
77 }
78
79 pub fn points(mut self, p: impl IntoIterator<Item = f64>) -> Self {
81 self.points = p.into_iter().filter(|v| v.is_finite()).collect();
82 self
83 }
84
85 pub fn outliers(mut self, o: impl IntoIterator<Item = f64>) -> Self {
87 self.outliers = o.into_iter().filter(|v| v.is_finite()).collect();
88 self
89 }
90
91 pub fn from_samples(samples: &[f64], k: f64) -> Option<Self> {
94 let mut s: Vec<f64> = samples.iter().copied().filter(|v| v.is_finite()).collect();
95 if s.is_empty() {
96 return None;
97 }
98 s.sort_by(|a, b| a.total_cmp(b));
99 let q = |p: f64| {
100 let pos = p * (s.len() - 1) as f64;
101 let (lo, hi) = (pos.floor() as usize, pos.ceil() as usize);
102 s[lo] + (s[hi] - s[lo]) * (pos - lo as f64)
103 };
104 let (q1, med, q3) = (q(0.25), q(0.5), q(0.75));
105 let k = if k.is_finite() && k >= 0.0 { k } else { 1.5 };
106 let iqr = q3 - q1;
107 let (lo_f, hi_f) = (q1 - k * iqr, q3 + k * iqr);
108 let mut inside = s.iter().filter(|v| **v >= lo_f && **v <= hi_f);
109 let min = inside.clone().next().copied().unwrap_or(q1);
110 let max = inside.next_back().copied().unwrap_or(q3);
111 let outliers = s
112 .iter()
113 .copied()
114 .filter(|v| *v < lo_f || *v > hi_f)
115 .collect();
116 let stride = (s.len() / 300).max(1);
117 Some(Self {
118 min,
119 q1,
120 median: med,
121 q3,
122 max,
123 outliers,
124 mean: Some(s.iter().sum::<f64>() / s.len() as f64),
125 n: s.len(),
126 points: s.iter().step_by(stride).copied().collect(),
127 })
128 }
129
130 fn valid(&self) -> bool {
131 [self.min, self.q1, self.median, self.q3, self.max]
132 .iter()
133 .all(|v| v.is_finite())
134 }
135}
136
137#[derive(Debug, Clone)]
138struct Group {
139 label: String,
140 stats: Option<BoxStats>,
141}
142
143#[derive(Debug, Clone)]
157pub struct BoxPlot {
158 groups: Vec<Group>,
159 colors: Option<Vec<Color>>,
160 theme: Option<Theme>,
161 base: Option<Style>,
162 orientation: BoxOrientation,
163 whisker_iqr: f64,
164 show_outliers: bool,
165 show_mean: bool,
166 notched: bool,
167 jitter: bool,
168 range: Option<(f64, f64)>,
169 block: Option<Block<'static>>,
170}
171
172impl Default for BoxPlot {
173 fn default() -> Self {
174 Self::new()
175 }
176}
177
178impl BoxPlot {
179 pub fn new() -> Self {
181 Self {
182 groups: vec![],
183 colors: None,
184 theme: None,
185 base: None,
186 orientation: BoxOrientation::Vertical,
187 whisker_iqr: 1.5,
188 show_outliers: true,
189 show_mean: true,
190 notched: false,
191 jitter: false,
192 range: None,
193 block: None,
194 }
195 }
196
197 pub fn group(
200 mut self,
201 label: impl Into<String>,
202 samples: impl IntoIterator<Item = f64>,
203 ) -> Self {
204 let v: Vec<f64> = samples.into_iter().collect();
205 self.groups.push(Group {
206 label: label.into(),
207 stats: BoxStats::from_samples(&v, self.whisker_iqr),
208 });
209 self
210 }
211
212 pub fn stats(mut self, label: impl Into<String>, stats: BoxStats) -> Self {
214 self.groups.push(Group {
215 label: label.into(),
216 stats: Some(stats),
217 });
218 self
219 }
220
221 setter!(
222 whisker_iqr: f64
224 );
225
226 pub fn colors(mut self, c: Vec<Color>) -> Self {
228 if !c.is_empty() {
229 self.colors = Some(c);
230 }
231 self
232 }
233
234 theme_setter!(
235 theme
238 );
239
240 base_style_setter!(base);
241
242 fn group_color(&self, i: usize) -> Color {
243 if let Some(c) = &self.colors {
244 return c[i % c.len()];
245 }
246 match &self.theme {
247 Some(t) => t.color(i),
248 None => [
249 Color::Cyan,
250 Color::Magenta,
251 Color::Yellow,
252 Color::Green,
253 Color::LightRed,
254 Color::LightBlue,
255 ][i % 6],
256 }
257 }
258
259 setter!(
260 orientation: BoxOrientation
262 );
263
264 setter!(
265 show_outliers: bool
267 );
268
269 setter!(
270 show_mean: bool
272 );
273
274 setter!(
275 notched: bool
278 );
279
280 setter!(
281 jitter: bool
284 );
285
286 pub fn range(mut self, min: f64, max: f64) -> Self {
288 self.range = Some((min, max));
289 self
290 }
291
292 block_setter!(block, 'static);
293
294 fn value_range(&self) -> (f64, f64) {
295 if let Some((a, b)) = self.range {
296 if a.is_finite() && b.is_finite() && b > a {
297 return (a, b);
298 }
299 }
300 let mut lo = f64::INFINITY;
301 let mut hi = f64::NEG_INFINITY;
302 for s in self
303 .groups
304 .iter()
305 .filter_map(|g| g.stats.as_ref())
306 .filter(|s| s.valid())
307 {
308 lo = lo.min(s.min);
309 hi = hi.max(s.max);
310 if self.show_outliers {
311 for &o in &s.outliers {
312 lo = lo.min(o);
313 hi = hi.max(o);
314 }
315 }
316 }
317 if !lo.is_finite() {
318 return (0.0, 1.0);
319 }
320 if hi <= lo {
321 return (lo - 1.0, hi + 1.0);
322 }
323 let pad = (hi - lo) * 0.05;
324 (lo - pad, hi + pad)
325 }
326}
327
328impl BoxPlot {
329 fn render_into(&self, area: Rect, buf: &mut Buffer) {
330 let area = area.intersection(buf.area);
331 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
332 if inner.width < 4 || inner.height < 3 || self.groups.is_empty() {
333 return;
334 }
335 let vert = self.orientation == BoxOrientation::Vertical;
336 let (lo, hi) = self.value_range();
337 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
338 let text = self
339 .theme
340 .as_ref()
341 .map_or(Style::default(), |t| t.label_style());
342 let ticks = |len: u16| nice_ticks(lo, hi, (len as usize / 4).max(2));
343 let step = |t: &[f64]| if t.len() >= 2 { t[1] - t[0] } else { 1.0 };
344
345 let (gutter, plot);
347 if vert {
348 let t = ticks(inner.height);
349 let w = t
350 .iter()
351 .map(|v| crate::util::format_tick(*v, step(&t)).chars().count())
352 .max()
353 .unwrap_or(1) as u16;
354 gutter = (w + 1).min(inner.width / 2);
355 plot = Rect::new(
356 inner.x + gutter,
357 inner.y,
358 inner.width - gutter,
359 inner.height - 1,
360 );
361 } else {
362 let w = self
363 .groups
364 .iter()
365 .map(|g| g.label.chars().count())
366 .max()
367 .unwrap_or(0) as u16;
368 gutter = (w + 1).min(inner.width / 3);
369 plot = Rect::new(
370 inner.x + gutter,
371 inner.y,
372 inner.width - gutter,
373 inner.height - 1,
374 );
375 }
376 if plot.width == 0 || plot.height == 0 {
377 return;
378 }
379 let (along_len, cross_len) = if vert {
380 (plot.height, plot.width)
381 } else {
382 (plot.width, plot.height)
383 };
384 let to_a = |v: f64| -> i32 {
385 let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
386 (f * (along_len - 1) as f64).round() as i32
387 };
388 let cell = |a: i32, c: i32| -> Option<(u16, u16)> {
389 if a < 0 || c < 0 || a >= along_len as i32 || c >= cross_len as i32 {
390 return None;
391 }
392 Some(if vert {
393 (plot.x + c as u16, plot.y + plot.height - 1 - a as u16)
394 } else {
395 (plot.x + a as u16, plot.y + c as u16)
396 })
397 };
398 let put = |buf: &mut Buffer, a: i32, c: i32, ch: char, st: Style| {
399 if let Some((x, y)) = cell(a, c) {
400 buf[(x, y)].set_char(ch).set_style(st);
401 }
402 };
403
404 let t = ticks(along_len);
406 let st = step(&t);
407 for v in &t {
408 let a = to_a(*v);
409 let label = crate::util::format_tick(*v, st);
410 if vert {
411 if let Some((_, y)) = cell(a, 0) {
412 let lw = label.chars().count() as u16;
413 put_str(
414 buf,
415 inner.x + gutter.saturating_sub(lw + 1),
416 y,
417 plot.x,
418 &label,
419 dim,
420 );
421 }
422 } else if let Some((x, _)) = cell(a, 0) {
423 put_str(buf, x, inner.bottom() - 1, inner.right(), &label, dim);
424 }
425 for c in 0..cross_len as i32 {
426 if let Some((x, y)) = cell(a, c) {
427 if buf[(x, y)].symbol() == " " {
428 buf[(x, y)].set_char('·').set_style(dim);
429 }
430 }
431 }
432 }
433
434 let n = self.groups.len();
436 let slot = (cross_len as f64 / n as f64).max(0.0);
437 for (i, g) in self.groups.iter().enumerate() {
438 let c0 = (i as f64 * slot).floor() as i32;
439 let c1 = (((i + 1) as f64 * slot).floor() as i32).max(c0 + 1);
440 let span = c1 - c0;
441 let bw = if span >= 5 { span - 2 } else { span.max(1) };
442 let bw = if vert { bw.min(15) } else { bw.min(5) };
443 let left = c0 + (span - bw) / 2;
444 let mid = left + bw / 2;
445 let color = self.group_color(i);
446 let s = Style::default().fg(color);
447 if let Some(st) = g.stats.as_ref().filter(|st| st.valid()) {
448 let (amin, amax) = (to_a(st.min), to_a(st.max));
449 let len = (amax - amin + 1).max(1) as u16;
450 let rect = if vert {
451 Rect::new(
452 plot.x + left as u16,
453 plot.y + plot.height - 1 - amax as u16,
454 bw as u16,
455 len,
456 )
457 } else {
458 Rect::new(plot.x + amin as u16, plot.y + left as u16, len, bw as u16)
459 }
460 .intersection(plot);
461 crate::interact::record_point(rect, 0, i, || {
462 let f = crate::util::format_compact;
463 let mut lines = vec![
464 format!("max {} q3 {}", f(st.max), f(st.q3)),
465 format!("median {}", f(st.median)),
466 format!("q1 {} min {}", f(st.q1), f(st.min)),
467 ];
468 if !st.outliers.is_empty() {
469 lines.push(format!("{} outliers", st.outliers.len()));
470 }
471 (g.label.clone(), lines)
472 });
473 }
474
475 if vert {
477 let w = span.max(0) as usize;
478 let l = trunc(&g.label, w);
479 let off = (w.saturating_sub(l.chars().count()) / 2) as u16;
480 put_str(
481 buf,
482 plot.x + c0 as u16 + off,
483 inner.bottom() - 1,
484 inner.right(),
485 &l,
486 text,
487 );
488 } else if let Some((_, y)) = cell(0, mid) {
489 put_str(
490 buf,
491 inner.x,
492 y,
493 plot.x,
494 &trunc(&g.label, gutter.saturating_sub(1) as usize),
495 text,
496 );
497 }
498
499 let Some(st) = g.stats.as_ref().filter(|s| s.valid()) else {
500 continue;
501 };
502 let (amin, aq1, amed, aq3, amax) = (
503 to_a(st.min),
504 to_a(st.q1),
505 to_a(st.median),
506 to_a(st.q3),
507 to_a(st.max),
508 );
509 let (wl, cp, ml) = if vert {
510 ('│', '─', '━')
511 } else {
512 ('─', '│', '┃')
513 };
514 for a in amin..aq1 {
515 put(buf, a, mid, wl, s);
516 }
517 for a in aq3 + 1..=amax {
518 put(buf, a, mid, wl, s);
519 }
520 let cw = (bw / 2).max(0);
521 for c in mid - cw / 2..=mid + cw / 2 {
522 put(buf, amin, c, cp, s);
523 put(buf, amax, c, cp, s);
524 }
525 for a in aq1..=aq3 {
526 for c in left..left + bw {
527 put(buf, a, c, '█', s);
528 }
529 }
530 let ms = Style::default()
531 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
532 .bg(color);
533 for c in left..left + bw {
534 put(buf, amed, c, ml, ms);
535 }
536 if self.notched && st.n > 1 && bw >= 5 {
538 let ci = 1.58 * (st.q3 - st.q1) / (st.n as f64).sqrt();
539 let (a0, a1) = (to_a(st.median - ci).max(aq1), to_a(st.median + ci).min(aq3));
540 for a in a0..=a1 {
541 put(buf, a, left, ' ', Style::default());
542 put(buf, a, left + bw - 1, ' ', Style::default());
543 }
544 if a0 > aq1 && a1 < aq3 {
545 for c in [left, left + bw - 1] {
546 put(buf, a0 - 1, c, if c == left { '┐' } else { '┌' }, s);
547 put(buf, a1 + 1, c, if c == left { '┘' } else { '└' }, s);
548 }
549 }
550 }
551 if self.jitter && bw >= 3 {
552 let ps =
553 Style::default().fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground));
554 for (k, &v) in st.points.iter().enumerate() {
555 if v < st.min || v > st.max {
556 continue;
557 }
558 let h = (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40;
560 let c = left + (h % bw as u64) as i32;
561 put(buf, to_a(v), c, '•', ps);
562 }
563 }
564 if self.show_mean {
565 if let Some(m) = st.mean.filter(|m| m.is_finite()) {
566 let ms = Style::default()
567 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
568 .bg(color);
569 put(buf, to_a(m), mid, '◆', ms);
570 }
571 }
572 if self.show_outliers {
573 for &o in &st.outliers {
574 let os = match (&self.colors, &self.theme) {
575 (None, Some(t)) => Style::default().fg(t.bear),
576 _ => s,
577 };
578 put(buf, to_a(o), mid, '○', os);
579 }
580 }
581 }
582 }
583}
584
585widget_impls!(BoxPlot);
586
587#[cfg(feature = "theme")]
588impl tui_nuances::Themed for BoxPlot {
589 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
590 self.theme(theme)
591 }
592}
593
594#[cfg(test)]
595mod tests {
596 use super::*;
597 use ratatui::widgets::Widget;
598
599 fn render(p: &BoxPlot, w: u16, h: u16) -> Buffer {
600 let area = Rect::new(0, 0, w, h);
601 let mut buf = Buffer::empty(area);
602 p.render(area, &mut buf);
603 buf
604 }
605
606 fn count(buf: &Buffer, sym: &str) -> usize {
607 buf.content().iter().filter(|c| c.symbol() == sym).count()
608 }
609
610 #[test]
611 fn quartiles_and_outlier() {
612 let mut v: Vec<f64> = (1..=9).map(|x| x as f64).collect();
613 v.push(100.0);
614 let s = BoxStats::from_samples(&v, 1.5).unwrap();
615 assert_eq!(s.median, 5.5);
616 assert_eq!(s.q1, 3.25);
617 assert_eq!(s.q3, 7.75);
618 assert_eq!(s.max, 9.0);
619 assert_eq!(s.outliers, vec![100.0]);
620 }
621
622 #[test]
623 fn empty_and_nan() {
624 assert!(BoxStats::from_samples(&[], 1.5).is_none());
625 assert!(BoxStats::from_samples(&[f64::NAN], 1.5).is_none());
626 }
627
628 #[test]
629 fn draws_box_median_outlier() {
630 let p = BoxPlot::new().group("a", (1..=9).map(|x| x as f64).chain([100.0]));
631 let b = render(&p, 30, 15);
632 let p2 = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
633 assert!(count(&render(&p2, 30, 15), "█") > 0);
634 assert!(count(&b, "━") > 0);
635 assert_eq!(count(&b, "○"), 1);
636 }
637
638 #[test]
639 fn mean_marker_toggle() {
640 let p = BoxPlot::new().group("a", (1..=20).map(|x| x as f64));
641 assert_eq!(count(&render(&p, 30, 15), "◆"), 1);
642 assert_eq!(count(&render(&p.clone().show_mean(false), 30, 15), "◆"), 0);
643 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
645 assert_eq!(count(&render(&q, 30, 15), "◆"), 0);
646 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0).mean(4.0));
647 assert_eq!(count(&render(&q, 30, 15), "◆"), 1);
648 }
649
650 #[test]
651 fn notches_change_box_only_with_sample_count() {
652 let samples = (1..=40).map(|x| x as f64);
653 let plain = render(&BoxPlot::new().group("a", samples.clone()), 30, 30);
654 let notched = render(&BoxPlot::new().group("a", samples).notched(true), 30, 30);
655 assert_ne!(plain, notched);
656 let unknown = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
657 assert_eq!(
658 render(&unknown, 30, 30),
659 render(&unknown.clone().notched(true), 30, 30)
660 );
661 }
662
663 #[test]
664 fn jitter_draws_points_deterministically() {
665 let p = BoxPlot::new()
666 .group("a", (1..=60).map(|x| x as f64))
667 .jitter(true);
668 let a = render(&p, 30, 20);
669 assert!(count(&a, "•") > 5);
670 assert_eq!(a, render(&p, 30, 20));
671 assert_eq!(
672 count(
673 &render(
674 &BoxPlot::new().group("a", (1..=60).map(|x| x as f64)),
675 30,
676 20
677 ),
678 "•"
679 ),
680 0
681 );
682 }
683
684 #[test]
685 fn horizontal_and_multi() {
686 let p = BoxPlot::new()
687 .stats("x", BoxStats::new(0.0, 2.0, 3.0, 4.0, 6.0))
688 .stats("y", BoxStats::new(1.0, 3.0, 5.0, 7.0, 9.0))
689 .orientation(BoxOrientation::Horizontal);
690 let b = render(&p, 40, 12);
691 assert!(count(&b, "┃") > 0);
692 }
693
694 #[cfg(feature = "theme")]
695 #[test]
696 fn theme_colors_and_override() {
697 let t = Theme::nord();
698 let p = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
699 let b = render(&p.clone().theme(&t), 30, 15);
700 assert!(b
701 .content()
702 .iter()
703 .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
704 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
705 let b = render(&p.theme(&t).colors(vec![Color::Red]), 30, 15);
706 assert!(b
707 .content()
708 .iter()
709 .any(|c| c.symbol() == "█" && c.fg == Color::Red));
710 assert!(!b
711 .content()
712 .iter()
713 .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
714 }
715
716 #[test]
717 fn tiny_areas_no_panic() {
718 let p = BoxPlot::new()
719 .group("a", [1.0, f64::NAN, 3.0])
720 .stats("n", BoxStats::new(f64::NAN, 0.0, 0.0, 0.0, 0.0))
721 .block(Block::bordered());
722 for w in 0..8 {
723 for h in 0..6 {
724 render(&p, w, h);
725 }
726 }
727 render(&BoxPlot::new(), 10, 5);
728 }
729}