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 && a.is_finite()
297 && b.is_finite()
298 && b > a
299 {
300 return (a, b);
301 }
302 let mut lo = f64::INFINITY;
303 let mut hi = f64::NEG_INFINITY;
304 for s in self
305 .groups
306 .iter()
307 .filter_map(|g| g.stats.as_ref())
308 .filter(|s| s.valid())
309 {
310 lo = lo.min(s.min);
311 hi = hi.max(s.max);
312 if self.show_outliers {
313 for &o in &s.outliers {
314 lo = lo.min(o);
315 hi = hi.max(o);
316 }
317 }
318 }
319 if !lo.is_finite() {
320 return (0.0, 1.0);
321 }
322 if hi <= lo {
323 return (lo - 1.0, hi + 1.0);
324 }
325 let pad = (hi - lo) * 0.05;
326 (lo - pad, hi + pad)
327 }
328}
329
330impl BoxPlot {
331 fn render_into(&self, area: Rect, buf: &mut Buffer) {
332 let area = area.intersection(buf.area);
333 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
334 if inner.width < 4 || inner.height < 3 || self.groups.is_empty() {
335 return;
336 }
337 let vert = self.orientation == BoxOrientation::Vertical;
338 let (lo, hi) = self.value_range();
339 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
340 let text = self
341 .theme
342 .as_ref()
343 .map_or(Style::default(), |t| t.label_style());
344 let ticks = |len: u16| nice_ticks(lo, hi, (len as usize / 4).max(2));
345 let step = |t: &[f64]| if t.len() >= 2 { t[1] - t[0] } else { 1.0 };
346
347 let (gutter, plot);
349 if vert {
350 let t = ticks(inner.height);
351 let w = t
352 .iter()
353 .map(|v| crate::util::format_tick(*v, step(&t)).chars().count())
354 .max()
355 .unwrap_or(1) as u16;
356 gutter = (w + 1).min(inner.width / 2);
357 plot = Rect::new(
358 inner.x + gutter,
359 inner.y,
360 inner.width - gutter,
361 inner.height - 1,
362 );
363 } else {
364 let w = self
365 .groups
366 .iter()
367 .map(|g| g.label.chars().count())
368 .max()
369 .unwrap_or(0) as u16;
370 gutter = (w + 1).min(inner.width / 3);
371 plot = Rect::new(
372 inner.x + gutter,
373 inner.y,
374 inner.width - gutter,
375 inner.height - 1,
376 );
377 }
378 if plot.width == 0 || plot.height == 0 {
379 return;
380 }
381 let (along_len, cross_len) = if vert {
382 (plot.height, plot.width)
383 } else {
384 (plot.width, plot.height)
385 };
386 let to_a = |v: f64| -> i32 {
387 let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
388 (f * (along_len - 1) as f64).round() as i32
389 };
390 let cell = |a: i32, c: i32| -> Option<(u16, u16)> {
391 if a < 0 || c < 0 || a >= along_len as i32 || c >= cross_len as i32 {
392 return None;
393 }
394 Some(if vert {
395 (plot.x + c as u16, plot.y + plot.height - 1 - a as u16)
396 } else {
397 (plot.x + a as u16, plot.y + c as u16)
398 })
399 };
400 let put = |buf: &mut Buffer, a: i32, c: i32, ch: char, st: Style| {
401 if let Some((x, y)) = cell(a, c) {
402 buf[(x, y)].set_char(ch).set_style(st);
403 }
404 };
405
406 let t = ticks(along_len);
408 let st = step(&t);
409 for v in &t {
410 let a = to_a(*v);
411 let label = crate::util::format_tick(*v, st);
412 if vert {
413 if let Some((_, y)) = cell(a, 0) {
414 let lw = label.chars().count() as u16;
415 put_str(
416 buf,
417 inner.x + gutter.saturating_sub(lw + 1),
418 y,
419 plot.x,
420 &label,
421 dim,
422 );
423 }
424 } else if let Some((x, _)) = cell(a, 0) {
425 put_str(buf, x, inner.bottom() - 1, inner.right(), &label, dim);
426 }
427 for c in 0..cross_len as i32 {
428 if let Some((x, y)) = cell(a, c)
429 && buf[(x, y)].symbol() == " "
430 {
431 buf[(x, y)].set_char('·').set_style(dim);
432 }
433 }
434 }
435
436 let n = self.groups.len();
438 let slot = (cross_len as f64 / n as f64).max(0.0);
439 for (i, g) in self.groups.iter().enumerate() {
440 let c0 = (i as f64 * slot).floor() as i32;
441 let c1 = (((i + 1) as f64 * slot).floor() as i32).max(c0 + 1);
442 let span = c1 - c0;
443 let bw = if span >= 5 { span - 2 } else { span.max(1) };
444 let bw = if vert { bw.min(15) } else { bw.min(5) };
445 let left = c0 + (span - bw) / 2;
446 let mid = left + bw / 2;
447 let color = self.group_color(i);
448 let s = Style::default().fg(color);
449 if let Some(st) = g.stats.as_ref().filter(|st| st.valid()) {
450 let (amin, amax) = (to_a(st.min), to_a(st.max));
451 let len = (amax - amin + 1).max(1) as u16;
452 let rect = if vert {
453 Rect::new(
454 plot.x + left as u16,
455 plot.y + plot.height - 1 - amax as u16,
456 bw as u16,
457 len,
458 )
459 } else {
460 Rect::new(plot.x + amin as u16, plot.y + left as u16, len, bw as u16)
461 }
462 .intersection(plot);
463 crate::interact::record_point(rect, 0, i, || {
464 let f = crate::util::format_compact;
465 let mut lines = vec![
466 format!("max {} q3 {}", f(st.max), f(st.q3)),
467 format!("median {}", f(st.median)),
468 format!("q1 {} min {}", f(st.q1), f(st.min)),
469 ];
470 if !st.outliers.is_empty() {
471 lines.push(format!("{} outliers", st.outliers.len()));
472 }
473 (g.label.clone(), lines)
474 });
475 }
476
477 if vert {
479 let w = span.max(0) as usize;
480 let l = trunc(&g.label, w);
481 let off = (w.saturating_sub(l.chars().count()) / 2) as u16;
482 put_str(
483 buf,
484 plot.x + c0 as u16 + off,
485 inner.bottom() - 1,
486 inner.right(),
487 &l,
488 text,
489 );
490 } else if let Some((_, y)) = cell(0, mid) {
491 put_str(
492 buf,
493 inner.x,
494 y,
495 plot.x,
496 &trunc(&g.label, gutter.saturating_sub(1) as usize),
497 text,
498 );
499 }
500
501 let Some(st) = g.stats.as_ref().filter(|s| s.valid()) else {
502 continue;
503 };
504 let (amin, aq1, amed, aq3, amax) = (
505 to_a(st.min),
506 to_a(st.q1),
507 to_a(st.median),
508 to_a(st.q3),
509 to_a(st.max),
510 );
511 let (wl, cp, ml) = if vert {
512 ('│', '─', '━')
513 } else {
514 ('─', '│', '┃')
515 };
516 for a in amin..aq1 {
517 put(buf, a, mid, wl, s);
518 }
519 for a in aq3 + 1..=amax {
520 put(buf, a, mid, wl, s);
521 }
522 let cw = (bw / 2).max(0);
523 for c in mid - cw / 2..=mid + cw / 2 {
524 put(buf, amin, c, cp, s);
525 put(buf, amax, c, cp, s);
526 }
527 for a in aq1..=aq3 {
528 for c in left..left + bw {
529 put(buf, a, c, '█', s);
530 }
531 }
532 let ms = Style::default()
533 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
534 .bg(color);
535 for c in left..left + bw {
536 put(buf, amed, c, ml, ms);
537 }
538 if self.notched && st.n > 1 && bw >= 5 {
540 let ci = 1.58 * (st.q3 - st.q1) / (st.n as f64).sqrt();
541 let (a0, a1) = (to_a(st.median - ci).max(aq1), to_a(st.median + ci).min(aq3));
542 for a in a0..=a1 {
543 put(buf, a, left, ' ', Style::default());
544 put(buf, a, left + bw - 1, ' ', Style::default());
545 }
546 if a0 > aq1 && a1 < aq3 {
547 for c in [left, left + bw - 1] {
548 put(buf, a0 - 1, c, if c == left { '┐' } else { '┌' }, s);
549 put(buf, a1 + 1, c, if c == left { '┘' } else { '└' }, s);
550 }
551 }
552 }
553 if self.jitter && bw >= 3 {
554 let ps =
555 Style::default().fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground));
556 for (k, &v) in st.points.iter().enumerate() {
557 if v < st.min || v > st.max {
558 continue;
559 }
560 let h = (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40;
562 let c = left + (h % bw as u64) as i32;
563 put(buf, to_a(v), c, '•', ps);
564 }
565 }
566 if self.show_mean
567 && let Some(m) = st.mean.filter(|m| m.is_finite())
568 {
569 let ms = Style::default()
570 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
571 .bg(color);
572 put(buf, to_a(m), mid, '◆', ms);
573 }
574 if self.show_outliers {
575 for &o in &st.outliers {
576 let os = match (&self.colors, &self.theme) {
577 (None, Some(t)) => Style::default().fg(t.bear),
578 _ => s,
579 };
580 put(buf, to_a(o), mid, '○', os);
581 }
582 }
583 }
584 }
585}
586
587widget_impls!(BoxPlot);
588
589#[cfg(feature = "theme")]
590impl tui_nuances::Themed for BoxPlot {
591 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
592 self.theme(theme)
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use ratatui::widgets::Widget;
600
601 fn render(p: &BoxPlot, w: u16, h: u16) -> Buffer {
602 let area = Rect::new(0, 0, w, h);
603 let mut buf = Buffer::empty(area);
604 p.render(area, &mut buf);
605 buf
606 }
607
608 fn count(buf: &Buffer, sym: &str) -> usize {
609 buf.content().iter().filter(|c| c.symbol() == sym).count()
610 }
611
612 #[test]
613 fn quartiles_and_outlier() {
614 let mut v: Vec<f64> = (1..=9).map(|x| x as f64).collect();
615 v.push(100.0);
616 let s = BoxStats::from_samples(&v, 1.5).unwrap();
617 assert_eq!(s.median, 5.5);
618 assert_eq!(s.q1, 3.25);
619 assert_eq!(s.q3, 7.75);
620 assert_eq!(s.max, 9.0);
621 assert_eq!(s.outliers, vec![100.0]);
622 }
623
624 #[test]
625 fn empty_and_nan() {
626 assert!(BoxStats::from_samples(&[], 1.5).is_none());
627 assert!(BoxStats::from_samples(&[f64::NAN], 1.5).is_none());
628 }
629
630 #[test]
631 fn draws_box_median_outlier() {
632 let p = BoxPlot::new().group("a", (1..=9).map(|x| x as f64).chain([100.0]));
633 let b = render(&p, 30, 15);
634 let p2 = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
635 assert!(count(&render(&p2, 30, 15), "█") > 0);
636 assert!(count(&b, "━") > 0);
637 assert_eq!(count(&b, "○"), 1);
638 }
639
640 #[test]
641 fn mean_marker_toggle() {
642 let p = BoxPlot::new().group("a", (1..=20).map(|x| x as f64));
643 assert_eq!(count(&render(&p, 30, 15), "◆"), 1);
644 assert_eq!(count(&render(&p.clone().show_mean(false), 30, 15), "◆"), 0);
645 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
647 assert_eq!(count(&render(&q, 30, 15), "◆"), 0);
648 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0).mean(4.0));
649 assert_eq!(count(&render(&q, 30, 15), "◆"), 1);
650 }
651
652 #[test]
653 fn notches_change_box_only_with_sample_count() {
654 let samples = (1..=40).map(|x| x as f64);
655 let plain = render(&BoxPlot::new().group("a", samples.clone()), 30, 30);
656 let notched = render(&BoxPlot::new().group("a", samples).notched(true), 30, 30);
657 assert_ne!(plain, notched);
658 let unknown = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
659 assert_eq!(
660 render(&unknown, 30, 30),
661 render(&unknown.clone().notched(true), 30, 30)
662 );
663 }
664
665 #[test]
666 fn jitter_draws_points_deterministically() {
667 let p = BoxPlot::new()
668 .group("a", (1..=60).map(|x| x as f64))
669 .jitter(true);
670 let a = render(&p, 30, 20);
671 assert!(count(&a, "•") > 5);
672 assert_eq!(a, render(&p, 30, 20));
673 assert_eq!(
674 count(
675 &render(
676 &BoxPlot::new().group("a", (1..=60).map(|x| x as f64)),
677 30,
678 20
679 ),
680 "•"
681 ),
682 0
683 );
684 }
685
686 #[test]
687 fn horizontal_and_multi() {
688 let p = BoxPlot::new()
689 .stats("x", BoxStats::new(0.0, 2.0, 3.0, 4.0, 6.0))
690 .stats("y", BoxStats::new(1.0, 3.0, 5.0, 7.0, 9.0))
691 .orientation(BoxOrientation::Horizontal);
692 let b = render(&p, 40, 12);
693 assert!(count(&b, "┃") > 0);
694 }
695
696 #[cfg(feature = "theme")]
697 #[test]
698 fn theme_colors_and_override() {
699 let t = Theme::nord();
700 let p = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
701 let b = render(&p.clone().theme(&t), 30, 15);
702 assert!(
703 b.content()
704 .iter()
705 .any(|c| c.symbol() == "█" && c.fg == t.color(0))
706 );
707 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
708 let b = render(&p.theme(&t).colors(vec![Color::Red]), 30, 15);
709 assert!(
710 b.content()
711 .iter()
712 .any(|c| c.symbol() == "█" && c.fg == Color::Red)
713 );
714 assert!(
715 !b.content()
716 .iter()
717 .any(|c| c.symbol() == "█" && c.fg == t.color(0))
718 );
719 }
720
721 #[test]
722 fn tiny_areas_no_panic() {
723 let p = BoxPlot::new()
724 .group("a", [1.0, f64::NAN, 3.0])
725 .stats("n", BoxStats::new(f64::NAN, 0.0, 0.0, 0.0, 0.0))
726 .block(Block::bordered());
727 for w in 0..8 {
728 for h in 0..6 {
729 render(&p, w, h);
730 }
731 }
732 render(&BoxPlot::new(), 10, 5);
733 }
734}