Skip to main content

tui_chart/
violin.rs

1//! Violin plot: mirrored kernel density per group with median and quartiles.
2
3use crate::canvas::{Canvas, Marker};
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{darken, dim_text, format_tick, nice_bounds, nice_ticks, pick};
7use ratatui::{
8    buffer::Buffer,
9    layout::Rect,
10    style::{Color, Style},
11    widgets::Block,
12};
13
14/// One violin: a label and its samples.
15#[derive(Debug, Clone, PartialEq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct ViolinGroup {
18    /// Group label.
19    pub label: String,
20    /// Samples; non-finite values are ignored.
21    pub samples: Vec<f64>,
22    /// Explicit color.
23    pub color: Option<Color>,
24}
25
26impl ViolinGroup {
27    /// Create a group.
28    pub fn new(label: impl Into<String>, samples: impl IntoIterator<Item = f64>) -> Self {
29        Self {
30            label: label.into(),
31            samples: samples.into_iter().collect(),
32            color: None,
33        }
34    }
35
36    /// Explicit color.
37    pub fn color(mut self, c: Color) -> Self {
38        self.color = Some(c);
39        self
40    }
41}
42
43/// Violin plot widget.
44///
45/// # Example
46///
47/// ```
48/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
49/// use tui_chart::{ViolinChart, ViolinGroup};
50///
51/// let chart = ViolinChart::new([ViolinGroup::new("a", (0..60).map(|i| (i % 13) as f64))]);
52/// let area = Rect::new(0, 0, 40, 12);
53/// let mut buf = Buffer::empty(area);
54/// chart.render(area, &mut buf);
55/// ```
56#[derive(Debug, Clone, Default)]
57pub struct ViolinChart {
58    groups: Vec<ViolinGroup>,
59    bandwidth: Option<f64>,
60    show_box: bool,
61    marker: Marker,
62    theme: Option<Theme>,
63    base: Option<Style>,
64    block: Option<Block<'static>>,
65}
66
67fn quantile(sorted: &[f64], q: f64) -> f64 {
68    let pos = q * (sorted.len() - 1) as f64;
69    let (i, f) = (pos.floor() as usize, pos.fract());
70    let j = (i + 1).min(sorted.len() - 1);
71    sorted[i] * (1.0 - f) + sorted[j] * f
72}
73
74impl ViolinChart {
75    /// Create a chart.
76    pub fn new(groups: impl IntoIterator<Item = ViolinGroup>) -> Self {
77        Self {
78            groups: groups.into_iter().collect(),
79            show_box: true,
80            ..Self::default()
81        }
82    }
83
84    opt_setter!(
85        /// Kernel bandwidth in data units (default: Silverman's rule).
86        bandwidth: f64
87    );
88    setter!(
89        /// Draw the inner quartile box and median dot (default on).
90        show_box: bool
91    );
92    setter!(
93        /// Dot resolution (default braille; half blocks fill solid but are coarser).
94        marker: Marker
95    );
96    theme_setter!(
97        /// Apply a [`Theme`]; explicit group colors win.
98        theme
99    );
100    base_style_setter!(base);
101    block_setter!(block, 'static);
102
103    fn render_into(&self, area: Rect, buf: &mut Buffer) {
104        let area = area.intersection(buf.area);
105        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
106        if inner.width < 8 || inner.height < 4 {
107            return;
108        }
109        let data: Vec<(usize, &ViolinGroup, Vec<f64>)> = self
110            .groups
111            .iter()
112            .enumerate()
113            .filter_map(|(i, g)| {
114                let mut s: Vec<f64> = g
115                    .samples
116                    .iter()
117                    .copied()
118                    .filter(|v| v.is_finite())
119                    .collect();
120                s.sort_by(f64::total_cmp);
121                (!s.is_empty()).then_some((i, g, s))
122            })
123            .collect();
124        if data.is_empty() {
125            return;
126        }
127        let lo = data.iter().map(|d| d.2[0]).fold(f64::MAX, f64::min);
128        let hi = data
129            .iter()
130            .map(|d| *d.2.last().unwrap())
131            .fold(f64::MIN, f64::max);
132        let (lo, hi) = nice_bounds(lo, hi, 5);
133        let span = (hi - lo).max(f64::EPSILON);
134        let (dim, text) = dim_text(&self.theme);
135
136        let ticks = nice_ticks(lo, hi, (inner.height as usize / 3).max(2));
137        let step = if ticks.len() >= 2 {
138            ticks[1] - ticks[0]
139        } else {
140            1.0
141        };
142        let labels: Vec<String> = ticks.iter().map(|t| format_tick(*t, step)).collect();
143        let gutter = (labels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
144            .min(inner.width / 2);
145        let plot = Rect::new(
146            inner.x + gutter,
147            inner.y,
148            inner.width - gutter,
149            inner.height - 1,
150        );
151        if plot.width < 2 || plot.height < 2 {
152            return;
153        }
154        for (t, l) in ticks.iter().zip(&labels) {
155            let f = ((t - lo) / span).clamp(0.0, 1.0);
156            let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
157            let w = l.chars().count() as u16;
158            put_str(
159                buf,
160                inner.x + gutter.saturating_sub(w + 1),
161                y,
162                plot.x,
163                l,
164                dim,
165            );
166            for x in plot.x..plot.right() {
167                buf[(x, y)].set_char('┈').set_style(dim);
168            }
169        }
170
171        let mut cv = Canvas::new(plot.width, plot.height, self.marker);
172        let (pw, ph) = (cv.px_w(), cv.px_h());
173        let slot = pw / data.len() as i32;
174        let ypx = |v: f64| ((1.0 - (v - lo) / span) * (ph - 1) as f64).round() as i32;
175        for (k, (i, g, s)) in data.iter().enumerate() {
176            let c = g.color.unwrap_or_else(|| pick(&self.theme, *i));
177            let fill = darken(c, 0.45);
178            let cx = slot * k as i32 + slot / 2;
179            let half = ((slot / 2) as f64 * 0.85) as i32;
180            let n = s.len();
181            let mean = s.iter().sum::<f64>() / n as f64;
182            let sd = (s.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n as f64).sqrt();
183            if crate::interact::recording() {
184                let (rx, ry) = self.marker.resolution();
185                let (rx, ry) = (i32::from(rx), i32::from(ry));
186                let (x_lo, x_hi) = ((cx - half).max(0) / rx, (cx + half).max(0) / rx);
187                let (y_lo, y_hi) = (ypx(s[n - 1]).max(0) / ry, ypx(s[0]).max(0) / ry);
188                let rect = Rect::new(
189                    plot.x + x_lo as u16,
190                    plot.y + y_lo as u16,
191                    (x_hi - x_lo + 1) as u16,
192                    (y_hi - y_lo + 1) as u16,
193                )
194                .intersection(plot);
195                crate::interact::record_point(rect, 0, *i, || {
196                    let f = crate::util::format_compact;
197                    (
198                        g.label.clone(),
199                        vec![
200                            format!("n {n}  mean {}", f(mean)),
201                            format!("median {}", f(quantile(s, 0.5))),
202                            format!("range {} .. {}", f(s[0]), f(s[n - 1])),
203                        ],
204                    )
205                });
206            }
207            let h = self
208                .bandwidth
209                .filter(|b| *b > 0.0)
210                .unwrap_or_else(|| {
211                    let bw = 1.06 * sd * (n as f64).powf(-0.2);
212                    if bw > 0.0 {
213                        bw
214                    } else {
215                        span / 20.0
216                    }
217                })
218                .max(span * 1e-6);
219            // cap work for huge inputs
220            let stride = (n / 2000).max(1);
221            let pts: Vec<f64> = s.iter().step_by(stride).copied().collect();
222            let dens: Vec<f64> = (0..ph)
223                .map(|py| {
224                    let v = hi - span * py as f64 / (ph - 1).max(1) as f64;
225                    pts.iter()
226                        .map(|x| (-0.5 * ((v - x) / h).powi(2)).exp())
227                        .sum::<f64>()
228                })
229                .collect();
230            let dmax = dens
231                .iter()
232                .copied()
233                .fold(0.0, f64::max)
234                .max(f64::MIN_POSITIVE);
235            let (smin, smax) = (ypx(s[n - 1]), ypx(s[0]));
236            for (py, d) in dens.iter().enumerate() {
237                let py = py as i32;
238                if py < smin - 2 || py > smax + 2 {
239                    continue;
240                }
241                let hw = (d / dmax * half as f64).round() as i32;
242                if hw <= 0 {
243                    continue;
244                }
245                for px in cx - hw..=cx + hw {
246                    cv.set(px, py, fill);
247                }
248                cv.set(cx - hw, py, c);
249                cv.set(cx + hw, py, c);
250            }
251            if self.show_box {
252                let (q1, med, q3) = (quantile(s, 0.25), quantile(s, 0.5), quantile(s, 0.75));
253                for py in ypx(q3)..=ypx(q1) {
254                    cv.set(cx, py, Color::White);
255                    cv.set(cx + 1, py, Color::White);
256                }
257                let m = ypx(med);
258                for (dx, dy) in [
259                    (0, 0),
260                    (1, 0),
261                    (-1, 0),
262                    (2, 0),
263                    (0, 1),
264                    (1, 1),
265                    (0, -1),
266                    (1, -1),
267                ] {
268                    cv.set(cx + dx, m + dy, c);
269                }
270            }
271        }
272        cv.render(buf, plot);
273        let slot_w = plot.width / data.len() as u16;
274        for (k, (_, g, _)) in data.iter().enumerate() {
275            let l: String = g.label.chars().take(slot_w as usize).collect();
276            let x =
277                plot.x + slot_w * k as u16 + slot_w.saturating_sub(l.chars().count() as u16) / 2;
278            put_str(buf, x, inner.bottom() - 1, inner.right(), &l, text);
279        }
280    }
281}
282
283widget_impls!(ViolinChart);
284
285#[cfg(feature = "theme")]
286impl tui_nuances::Themed for ViolinChart {
287    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
288        self.theme(theme)
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use ratatui::widgets::Widget;
296
297    fn render(c: &ViolinChart, w: u16, h: u16) -> Buffer {
298        let a = Rect::new(0, 0, w, h);
299        let mut b = Buffer::empty(a);
300        c.render(a, &mut b);
301        b
302    }
303
304    fn bell(mu: f64, sd: f64) -> Vec<f64> {
305        (0..200)
306            .map(|i| {
307                mu + sd * (((i as f64) * 0.618).fract() * 2.0 - 1.0) * 1.7
308                    + sd * ((i % 7) as f64 - 3.0) * 0.2
309            })
310            .collect()
311    }
312
313    fn chart() -> ViolinChart {
314        ViolinChart::new([
315            ViolinGroup::new("a", bell(5.0, 1.0)).color(Color::Red),
316            ViolinGroup::new("b", bell(8.0, 2.0)).color(Color::Blue),
317        ])
318    }
319
320    #[test]
321    fn draws_groups_in_their_colors_with_labels() {
322        let b = render(&chart(), 60, 20);
323        let t: String = b.content().iter().map(|c| c.symbol()).collect();
324        assert!(t.contains('a') && t.contains('b'));
325        assert!(b.content().iter().any(|c| c.fg == Color::Red));
326        assert!(b.content().iter().any(|c| c.fg == Color::Blue));
327    }
328
329    #[test]
330    fn wider_spread_covers_more_cells() {
331        let count = |sd: f64| {
332            let c = ViolinChart::new([ViolinGroup::new("x", bell(5.0, sd)).color(Color::Red)])
333                .show_box(false);
334            render(&c, 40, 20)
335                .content()
336                .iter()
337                .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::Reset)
338                .count()
339        };
340        assert!(count(3.0) > count(0.3));
341    }
342
343    #[test]
344    fn box_toggle_changes_output() {
345        let on = render(&chart(), 60, 20);
346        let off = render(&chart().show_box(false), 60, 20);
347        assert_ne!(on, off);
348        assert!(on.content().iter().any(|c| c.fg == Color::White));
349    }
350
351    #[test]
352    fn explicit_bandwidth_smooths() {
353        let narrow = render(&chart().bandwidth(0.05), 60, 20);
354        let wide = render(&chart().bandwidth(3.0), 60, 20);
355        assert_ne!(narrow, wide);
356    }
357
358    #[test]
359    fn degenerate_inputs_do_not_panic() {
360        let c = ViolinChart::new([
361            ViolinGroup::new("nan", [f64::NAN, f64::INFINITY]),
362            ViolinGroup::new("one", [3.0]),
363            ViolinGroup::new("same", [2.0, 2.0, 2.0]),
364            ViolinGroup::new("big", [-1e300, 1e300]),
365        ]);
366        for (w, h) in [(0, 0), (1, 1), (8, 4), (3, 40), (200, 60)] {
367            render(&c, w, h);
368            render(&chart(), w, h);
369        }
370        render(&ViolinChart::new([]), 40, 10);
371    }
372}