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
448 if vert {
450 let w = span.max(0) as usize;
451 let l = trunc(&g.label, w);
452 let off = (w.saturating_sub(l.chars().count()) / 2) as u16;
453 put_str(
454 buf,
455 plot.x + c0 as u16 + off,
456 inner.bottom() - 1,
457 inner.right(),
458 &l,
459 text,
460 );
461 } else if let Some((_, y)) = cell(0, mid) {
462 put_str(
463 buf,
464 inner.x,
465 y,
466 plot.x,
467 &trunc(&g.label, gutter.saturating_sub(1) as usize),
468 text,
469 );
470 }
471
472 let Some(st) = g.stats.as_ref().filter(|s| s.valid()) else {
473 continue;
474 };
475 let (amin, aq1, amed, aq3, amax) = (
476 to_a(st.min),
477 to_a(st.q1),
478 to_a(st.median),
479 to_a(st.q3),
480 to_a(st.max),
481 );
482 let (wl, cp, ml) = if vert {
483 ('│', '─', '━')
484 } else {
485 ('─', '│', '┃')
486 };
487 for a in amin..aq1 {
488 put(buf, a, mid, wl, s);
489 }
490 for a in aq3 + 1..=amax {
491 put(buf, a, mid, wl, s);
492 }
493 let cw = (bw / 2).max(0);
494 for c in mid - cw / 2..=mid + cw / 2 {
495 put(buf, amin, c, cp, s);
496 put(buf, amax, c, cp, s);
497 }
498 for a in aq1..=aq3 {
499 for c in left..left + bw {
500 put(buf, a, c, '█', s);
501 }
502 }
503 let ms = Style::default()
504 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
505 .bg(color);
506 for c in left..left + bw {
507 put(buf, amed, c, ml, ms);
508 }
509 if self.notched && st.n > 1 && bw >= 5 {
511 let ci = 1.58 * (st.q3 - st.q1) / (st.n as f64).sqrt();
512 let (a0, a1) = (to_a(st.median - ci).max(aq1), to_a(st.median + ci).min(aq3));
513 for a in a0..=a1 {
514 put(buf, a, left, ' ', Style::default());
515 put(buf, a, left + bw - 1, ' ', Style::default());
516 }
517 if a0 > aq1 && a1 < aq3 {
518 for c in [left, left + bw - 1] {
519 put(buf, a0 - 1, c, if c == left { '┐' } else { '┌' }, s);
520 put(buf, a1 + 1, c, if c == left { '┘' } else { '└' }, s);
521 }
522 }
523 }
524 if self.jitter && bw >= 3 {
525 let ps =
526 Style::default().fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground));
527 for (k, &v) in st.points.iter().enumerate() {
528 if v < st.min || v > st.max {
529 continue;
530 }
531 let h = (k as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40;
533 let c = left + (h % bw as u64) as i32;
534 put(buf, to_a(v), c, '•', ps);
535 }
536 }
537 if self.show_mean {
538 if let Some(m) = st.mean.filter(|m| m.is_finite()) {
539 let ms = Style::default()
540 .fg(self.theme.as_ref().map_or(Color::White, |t| t.foreground))
541 .bg(color);
542 put(buf, to_a(m), mid, '◆', ms);
543 }
544 }
545 if self.show_outliers {
546 for &o in &st.outliers {
547 let os = match (&self.colors, &self.theme) {
548 (None, Some(t)) => Style::default().fg(t.bear),
549 _ => s,
550 };
551 put(buf, to_a(o), mid, '○', os);
552 }
553 }
554 }
555 }
556}
557
558widget_impls!(BoxPlot);
559
560#[cfg(feature = "theme")]
561impl tui_nuances::Themed for BoxPlot {
562 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
563 self.theme(theme)
564 }
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use ratatui::widgets::Widget;
571
572 fn render(p: &BoxPlot, w: u16, h: u16) -> Buffer {
573 let area = Rect::new(0, 0, w, h);
574 let mut buf = Buffer::empty(area);
575 p.render(area, &mut buf);
576 buf
577 }
578
579 fn count(buf: &Buffer, sym: &str) -> usize {
580 buf.content().iter().filter(|c| c.symbol() == sym).count()
581 }
582
583 #[test]
584 fn quartiles_and_outlier() {
585 let mut v: Vec<f64> = (1..=9).map(|x| x as f64).collect();
586 v.push(100.0);
587 let s = BoxStats::from_samples(&v, 1.5).unwrap();
588 assert_eq!(s.median, 5.5);
589 assert_eq!(s.q1, 3.25);
590 assert_eq!(s.q3, 7.75);
591 assert_eq!(s.max, 9.0);
592 assert_eq!(s.outliers, vec![100.0]);
593 }
594
595 #[test]
596 fn empty_and_nan() {
597 assert!(BoxStats::from_samples(&[], 1.5).is_none());
598 assert!(BoxStats::from_samples(&[f64::NAN], 1.5).is_none());
599 }
600
601 #[test]
602 fn draws_box_median_outlier() {
603 let p = BoxPlot::new().group("a", (1..=9).map(|x| x as f64).chain([100.0]));
604 let b = render(&p, 30, 15);
605 let p2 = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
606 assert!(count(&render(&p2, 30, 15), "█") > 0);
607 assert!(count(&b, "━") > 0);
608 assert_eq!(count(&b, "○"), 1);
609 }
610
611 #[test]
612 fn mean_marker_toggle() {
613 let p = BoxPlot::new().group("a", (1..=20).map(|x| x as f64));
614 assert_eq!(count(&render(&p, 30, 15), "◆"), 1);
615 assert_eq!(count(&render(&p.clone().show_mean(false), 30, 15), "◆"), 0);
616 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
618 assert_eq!(count(&render(&q, 30, 15), "◆"), 0);
619 let q = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0).mean(4.0));
620 assert_eq!(count(&render(&q, 30, 15), "◆"), 1);
621 }
622
623 #[test]
624 fn notches_change_box_only_with_sample_count() {
625 let samples = (1..=40).map(|x| x as f64);
626 let plain = render(&BoxPlot::new().group("a", samples.clone()), 30, 30);
627 let notched = render(&BoxPlot::new().group("a", samples).notched(true), 30, 30);
628 assert_ne!(plain, notched);
629 let unknown = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
630 assert_eq!(
631 render(&unknown, 30, 30),
632 render(&unknown.clone().notched(true), 30, 30)
633 );
634 }
635
636 #[test]
637 fn jitter_draws_points_deterministically() {
638 let p = BoxPlot::new()
639 .group("a", (1..=60).map(|x| x as f64))
640 .jitter(true);
641 let a = render(&p, 30, 20);
642 assert!(count(&a, "•") > 5);
643 assert_eq!(a, render(&p, 30, 20));
644 assert_eq!(
645 count(
646 &render(
647 &BoxPlot::new().group("a", (1..=60).map(|x| x as f64)),
648 30,
649 20
650 ),
651 "•"
652 ),
653 0
654 );
655 }
656
657 #[test]
658 fn horizontal_and_multi() {
659 let p = BoxPlot::new()
660 .stats("x", BoxStats::new(0.0, 2.0, 3.0, 4.0, 6.0))
661 .stats("y", BoxStats::new(1.0, 3.0, 5.0, 7.0, 9.0))
662 .orientation(BoxOrientation::Horizontal);
663 let b = render(&p, 40, 12);
664 assert!(count(&b, "┃") > 0);
665 }
666
667 #[cfg(feature = "theme")]
668 #[test]
669 fn theme_colors_and_override() {
670 let t = Theme::nord();
671 let p = BoxPlot::new().stats("a", BoxStats::new(0.0, 2.0, 5.0, 8.0, 10.0));
672 let b = render(&p.clone().theme(&t), 30, 15);
673 assert!(b
674 .content()
675 .iter()
676 .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
677 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
678 let b = render(&p.theme(&t).colors(vec![Color::Red]), 30, 15);
679 assert!(b
680 .content()
681 .iter()
682 .any(|c| c.symbol() == "█" && c.fg == Color::Red));
683 assert!(!b
684 .content()
685 .iter()
686 .any(|c| c.symbol() == "█" && c.fg == t.color(0)));
687 }
688
689 #[test]
690 fn tiny_areas_no_panic() {
691 let p = BoxPlot::new()
692 .group("a", [1.0, f64::NAN, 3.0])
693 .stats("n", BoxStats::new(f64::NAN, 0.0, 0.0, 0.0, 0.0))
694 .block(Block::bordered());
695 for w in 0..8 {
696 for h in 0..6 {
697 render(&p, w, h);
698 }
699 }
700 render(&BoxPlot::new(), 10, 5);
701 }
702}