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().copied().unwrap_or(f64::MIN))
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 { bw } else { span / 20.0 }
213                })
214                .max(span * 1e-6);
215            // cap work for huge inputs
216            let stride = (n / 2000).max(1);
217            let pts: Vec<f64> = s.iter().step_by(stride).copied().collect();
218            let dens: Vec<f64> = (0..ph)
219                .map(|py| {
220                    let v = hi - span * py as f64 / (ph - 1).max(1) as f64;
221                    pts.iter()
222                        .map(|x| (-0.5 * ((v - x) / h).powi(2)).exp())
223                        .sum::<f64>()
224                })
225                .collect();
226            let dmax = dens
227                .iter()
228                .copied()
229                .fold(0.0, f64::max)
230                .max(f64::MIN_POSITIVE);
231            let (smin, smax) = (ypx(s[n - 1]), ypx(s[0]));
232            for (py, d) in dens.iter().enumerate() {
233                let py = py as i32;
234                if py < smin - 2 || py > smax + 2 {
235                    continue;
236                }
237                let hw = (d / dmax * half as f64).round() as i32;
238                if hw <= 0 {
239                    continue;
240                }
241                for px in cx - hw..=cx + hw {
242                    cv.set(px, py, fill);
243                }
244                cv.set(cx - hw, py, c);
245                cv.set(cx + hw, py, c);
246            }
247            if self.show_box {
248                let (q1, med, q3) = (quantile(s, 0.25), quantile(s, 0.5), quantile(s, 0.75));
249                for py in ypx(q3)..=ypx(q1) {
250                    cv.set(cx, py, Color::White);
251                    cv.set(cx + 1, py, Color::White);
252                }
253                let m = ypx(med);
254                for (dx, dy) in [
255                    (0, 0),
256                    (1, 0),
257                    (-1, 0),
258                    (2, 0),
259                    (0, 1),
260                    (1, 1),
261                    (0, -1),
262                    (1, -1),
263                ] {
264                    cv.set(cx + dx, m + dy, c);
265                }
266            }
267        }
268        cv.render(buf, plot);
269        let slot_w = plot.width / data.len() as u16;
270        for (k, (_, g, _)) in data.iter().enumerate() {
271            let l: String = g.label.chars().take(slot_w as usize).collect();
272            let x =
273                plot.x + slot_w * k as u16 + slot_w.saturating_sub(l.chars().count() as u16) / 2;
274            put_str(buf, x, inner.bottom() - 1, inner.right(), &l, text);
275        }
276    }
277}
278
279widget_impls!(ViolinChart);
280
281#[cfg(feature = "theme")]
282impl tui_nuances::Themed for ViolinChart {
283    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
284        self.theme(theme)
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use ratatui::widgets::Widget;
292
293    fn render(c: &ViolinChart, w: u16, h: u16) -> Buffer {
294        let a = Rect::new(0, 0, w, h);
295        let mut b = Buffer::empty(a);
296        c.render(a, &mut b);
297        b
298    }
299
300    fn bell(mu: f64, sd: f64) -> Vec<f64> {
301        (0..200)
302            .map(|i| {
303                mu + sd * (((i as f64) * 0.618).fract() * 2.0 - 1.0) * 1.7
304                    + sd * ((i % 7) as f64 - 3.0) * 0.2
305            })
306            .collect()
307    }
308
309    fn chart() -> ViolinChart {
310        ViolinChart::new([
311            ViolinGroup::new("a", bell(5.0, 1.0)).color(Color::Red),
312            ViolinGroup::new("b", bell(8.0, 2.0)).color(Color::Blue),
313        ])
314    }
315
316    #[test]
317    fn draws_groups_in_their_colors_with_labels() {
318        let b = render(&chart(), 60, 20);
319        let t: String = b.content().iter().map(|c| c.symbol()).collect();
320        assert!(t.contains('a') && t.contains('b'));
321        assert!(b.content().iter().any(|c| c.fg == Color::Red));
322        assert!(b.content().iter().any(|c| c.fg == Color::Blue));
323    }
324
325    #[test]
326    fn wider_spread_covers_more_cells() {
327        let count = |sd: f64| {
328            let c = ViolinChart::new([ViolinGroup::new("x", bell(5.0, sd)).color(Color::Red)])
329                .show_box(false);
330            render(&c, 40, 20)
331                .content()
332                .iter()
333                .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::Reset)
334                .count()
335        };
336        assert!(count(3.0) > count(0.3));
337    }
338
339    #[test]
340    fn box_toggle_changes_output() {
341        let on = render(&chart(), 60, 20);
342        let off = render(&chart().show_box(false), 60, 20);
343        assert_ne!(on, off);
344        assert!(on.content().iter().any(|c| c.fg == Color::White));
345    }
346
347    #[test]
348    fn explicit_bandwidth_smooths() {
349        let narrow = render(&chart().bandwidth(0.05), 60, 20);
350        let wide = render(&chart().bandwidth(3.0), 60, 20);
351        assert_ne!(narrow, wide);
352    }
353
354    #[test]
355    fn degenerate_inputs_do_not_panic() {
356        let c = ViolinChart::new([
357            ViolinGroup::new("nan", [f64::NAN, f64::INFINITY]),
358            ViolinGroup::new("one", [3.0]),
359            ViolinGroup::new("same", [2.0, 2.0, 2.0]),
360            ViolinGroup::new("big", [-1e300, 1e300]),
361        ]);
362        for (w, h) in [(0, 0), (1, 1), (8, 4), (3, 40), (200, 60)] {
363            render(&c, w, h);
364            render(&chart(), w, h);
365        }
366        render(&ViolinChart::new([]), 40, 10);
367    }
368}