Skip to main content

tui_chart/
histogram.rs

1//! Histogram: bins raw samples and renders them as bars.
2
3use crate::axis::Axis;
4use crate::bar::{BarChart, BarGroup, BarOrientation};
5use crate::canvas::{Canvas, Marker};
6use crate::heatmap::Gradient;
7use crate::theme::Theme;
8use crate::util::{format_tick, nice_step};
9use ratatui::{
10    buffer::Buffer,
11    layout::Rect,
12    style::{Color, Style},
13    widgets::{Block, Widget},
14};
15
16/// One histogram bin `[start, end)` (last bin includes `end`).
17#[derive(Debug, Clone, Copy, PartialEq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct Bin {
20    /// Inclusive lower edge.
21    pub start: f64,
22    /// Upper edge.
23    pub end: f64,
24    /// Number of samples.
25    pub count: usize,
26}
27
28/// Histogram widget.
29#[derive(Debug, Clone)]
30pub struct Histogram {
31    data: Vec<f64>,
32    bins: Option<usize>,
33    range: Option<(f64, f64)>,
34    color: Option<Color>,
35    kde: bool,
36    stats: bool,
37    kde_bandwidth: Option<f64>,
38    gradient: Option<Gradient>,
39    theme: Option<Theme>,
40    style: Option<Style>,
41    orientation: BarOrientation,
42    show_values: bool,
43    cumulative: bool,
44    normalized: bool,
45    marker: Marker,
46    bar_marker: Option<Marker>,
47    block: Option<Block<'static>>,
48    value_axis: Axis,
49}
50
51impl Histogram {
52    /// Create from samples (non-finite values are ignored).
53    pub fn new(data: impl IntoIterator<Item = f64>) -> Self {
54        Self {
55            data: data.into_iter().filter(|v| v.is_finite()).collect(),
56            bins: None,
57            range: None,
58            color: None,
59            kde: false,
60            stats: false,
61            kde_bandwidth: None,
62            gradient: None,
63            theme: None,
64            style: None,
65            orientation: BarOrientation::Vertical,
66            show_values: false,
67            cumulative: false,
68            normalized: false,
69            marker: Marker::Braille,
70            bar_marker: None,
71            block: None,
72            value_axis: Axis::new().grid(true),
73        }
74    }
75
76    /// Fixed bin count (default: Sturges' rule).
77    pub fn bins(mut self, n: usize) -> Self {
78        self.bins = Some(n.max(1));
79        self
80    }
81
82    /// Fixed sample range.
83    pub fn range(mut self, min: f64, max: f64) -> Self {
84        self.range = Some((min, max));
85        self
86    }
87
88    opt_setter!(
89        /// Bar color.
90        color: Color
91    );
92
93    setter!(
94        /// Overlay a Gaussian kernel density estimate curve on the bars
95        /// (vertical, non-cumulative histograms only; ignored otherwise).
96        /// The curve is scaled to the bar units (counts, or density when normalized).
97        kde: bool
98    );
99
100    setter!(
101        /// Mark the mean (`μ`) and median (`med`) with labelled vertical lines
102        /// (vertical, non-cumulative histograms only).
103        stats: bool
104    );
105
106    opt_setter!(
107        /// KDE bandwidth (default: Silverman's rule). Implies nothing unless
108        /// [`Histogram::kde`] is on.
109        kde_bandwidth: f64
110    );
111
112    opt_setter!(
113        /// Color bars by height using a gradient (instead of one flat color).
114        gradient: Gradient
115    );
116
117    /// Apply a [`Theme`] (accent bar color, axes, background). An explicit
118    /// [`Histogram::color`] wins.
119    #[cfg(feature = "theme")]
120    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
121        let t = theme.into();
122        self.value_axis.theme_in_place(&t);
123        self.theme = Some(t);
124        self
125    }
126
127    base_style_setter!(style);
128
129    setter!(
130        /// Bar direction.
131        orientation: BarOrientation
132    );
133
134    setter!(
135        /// Print counts.
136        show_values: bool
137    );
138
139    setter!(
140        /// Cumulative mode: each bar shows the running total up to and including its bin.
141        cumulative: bool
142    );
143
144    setter!(
145        /// Normalized mode: bars show probability density (area = 1); combined with
146        /// [`cumulative`](Self::cumulative) the last bar reaches 1.
147        normalized: bool
148    );
149
150    opt_setter!(
151        /// Draw the bars with dot glyphs (see [`BarChart::marker`]). Default:
152        /// eighth blocks.
153        bar_marker: Marker
154    );
155
156    setter!(
157        /// Glyph family of the KDE curve (default [`Marker::Braille`]).
158        marker: Marker
159    );
160
161    block_setter!(block, 'static);
162
163    /// Count axis.
164    pub fn value_axis(mut self, a: Axis) -> Self {
165        self.value_axis = a;
166        if let Some(t) = &self.theme {
167            self.value_axis.theme_in_place(t);
168        }
169        self
170    }
171
172    /// Compute the bins.
173    pub fn compute_bins(&self) -> Vec<Bin> {
174        if self.data.is_empty() {
175            return vec![];
176        }
177        let n = self
178            .bins
179            .unwrap_or_else(|| ((self.data.len() as f64).log2().ceil() as usize + 1).clamp(1, 64));
180        let (lo, hi) = self.range.unwrap_or_else(|| {
181            let lo = self.data.iter().cloned().fold(f64::INFINITY, f64::min);
182            let hi = self.data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
183            (lo, hi)
184        });
185        let (lo, hi) = if hi <= lo {
186            (lo - 0.5, hi + 0.5)
187        } else {
188            (lo, hi)
189        };
190        let width = (hi - lo) / n as f64;
191        let mut bins: Vec<Bin> = (0..n)
192            .map(|i| Bin {
193                start: lo + i as f64 * width,
194                end: lo + (i + 1) as f64 * width,
195                count: 0,
196            })
197            .collect();
198        for &v in &self.data {
199            if v < lo || v > hi {
200                continue;
201            }
202            let i = (((v - lo) / width) as usize).min(n - 1);
203            bins[i].count += 1;
204        }
205        bins
206    }
207
208    /// Bar heights per bin, honouring the cumulative / normalized modes.
209    pub fn heights(&self) -> Vec<f64> {
210        let bins = self.compute_bins();
211        let total: usize = bins.iter().map(|b| b.count).sum();
212        let mut acc = 0.0;
213        bins.iter()
214            .map(|b| {
215                let mut v = b.count as f64;
216                if self.normalized && total > 0 {
217                    v /= total as f64;
218                    if !self.cumulative {
219                        v /= (b.end - b.start).abs().max(f64::MIN_POSITIVE);
220                    }
221                }
222                if self.cumulative {
223                    acc += v;
224                    acc
225                } else {
226                    v
227                }
228            })
229            .collect()
230    }
231
232    /// Gaussian kernel density estimate sampled at `points` evenly spaced x
233    /// values across the bin range, as `(x, density)` pairs ready for a
234    /// [`Series`](crate::Series). `bandwidth` of `None` uses Silverman's rule.
235    /// Scale by `n * bin_width` to overlay on a count histogram.
236    pub fn kde_curve(&self, points: usize, bandwidth: Option<f64>) -> Vec<(f64, f64)> {
237        let bins = self.compute_bins();
238        let (Some(first), Some(last)) = (bins.first(), bins.last()) else {
239            return vec![];
240        };
241        let (lo, hi) = (first.start, last.end);
242        let n = self.data.len() as f64;
243        let mean = self.data.iter().sum::<f64>() / n;
244        let sd = (self.data.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n).sqrt();
245        let h = bandwidth
246            .filter(|h| h.is_finite() && *h > 0.0)
247            .unwrap_or_else(|| {
248                let h = 1.06 * sd * n.powf(-0.2);
249                if h.is_finite() && h > 0.0 {
250                    h
251                } else {
252                    (hi - lo) / 10.0
253                }
254            });
255        let points = points.max(2);
256        let norm = 1.0 / (n * h * (2.0 * std::f64::consts::PI).sqrt());
257        (0..points)
258            .map(|i| {
259                let x = lo + (hi - lo) * i as f64 / (points - 1) as f64;
260                let d: f64 = self
261                    .data
262                    .iter()
263                    .map(|v| (-0.5 * ((x - v) / h).powi(2)).exp())
264                    .sum();
265                (x, d * norm)
266            })
267            .collect()
268    }
269
270    fn to_bar_chart(&self) -> BarChart {
271        let bins = self.compute_bins();
272        let step = bins
273            .first()
274            .map(|b| nice_step((b.end - b.start).abs() / 2.0))
275            .unwrap_or(1.0);
276        let heights = self.heights();
277        let groups: Vec<BarGroup> = bins
278            .iter()
279            .zip(heights)
280            .map(|(b, h)| BarGroup::new(format_tick(b.start, step.min(b.end - b.start)), [h]))
281            .collect();
282        let mut chart = BarChart::new(groups)
283            .colors(vec![self.bar_color()])
284            .orientation(self.orientation)
285            .show_values(self.show_values)
286            .group_gap(0)
287            .value_axis(self.value_axis.clone());
288        if let Some(b) = self.block.clone() {
289            chart = chart.block(b);
290        }
291        #[cfg(feature = "theme")]
292        if let Some(t) = &self.theme {
293            chart = chart.theme(t);
294        }
295        if let Some(s) = self.style {
296            chart = chart.base_style(s);
297        }
298        if let Some(m) = self.bar_marker {
299            chart = chart.marker(m);
300        }
301        if let Some(g) = &self.gradient {
302            chart = chart.gradient(g.clone());
303        }
304        chart
305    }
306
307    fn bar_color(&self) -> Color {
308        self.color
309            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.accent))
310    }
311
312    fn draw_kde(&self, chart: &BarChart, area: Rect, buf: &mut Buffer) {
313        let bins = self.compute_bins();
314        let Some(first) = bins.first() else { return };
315        let Some((plot, lo, hi, bw)) = chart.vertical_geometry(area) else {
316            return;
317        };
318        let span = bins.len() as u16 * bw;
319        if span == 0 || span > plot.width || hi <= lo {
320            return;
321        }
322        let bin_w = (first.end - first.start).abs();
323        let n = self.data.len() as f64;
324        let scale = if self.normalized { 1.0 } else { n * bin_w };
325        let curve = self.kde_curve((span as usize * 2).max(8), self.kde_bandwidth);
326        let (x0, x1) = (first.start, bins[bins.len() - 1].end);
327        let mut canvas = Canvas::new(span, plot.height, self.marker);
328        let (pw, ph) = (f64::from(canvas.px_w()), f64::from(canvas.px_h()));
329        let color = self.theme.as_ref().map_or(Color::Yellow, |t| t.color(1));
330        let mut prev: Option<(i32, i32)> = None;
331        for (x, d) in curve {
332            let fx = ((x - x0) / (x1 - x0)).clamp(0.0, 1.0);
333            let fy = ((d * scale - lo) / (hi - lo)).clamp(0.0, 1.0);
334            let p = (
335                (fx * (pw - 1.0)).round() as i32,
336                ((1.0 - fy) * (ph - 1.0)).round() as i32,
337            );
338            if let Some(q) = prev {
339                canvas.line(q.0, q.1, p.0, p.1, color);
340            }
341            prev = Some(p);
342        }
343        canvas.render(buf, Rect::new(plot.x, plot.y, span, plot.height));
344    }
345
346    fn draw_stats(&self, chart: &BarChart, area: Rect, buf: &mut Buffer) {
347        let bins = self.compute_bins();
348        let Some(first) = bins.first() else { return };
349        let Some((plot, ..)) = chart.vertical_geometry(area) else {
350            return;
351        };
352        let bw = chart.vertical_geometry(area).map_or(0, |g| g.3);
353        let span = bins.len() as u16 * bw;
354        let (x0, x1) = (first.start, bins[bins.len() - 1].end);
355        if span == 0 || span > plot.width || x1 <= x0 || self.data.is_empty() {
356            return;
357        }
358        let mut sorted = self.data.clone();
359        sorted.sort_by(|a, b| a.total_cmp(b));
360        let n = sorted.len();
361        let mean = sorted.iter().sum::<f64>() / n as f64;
362        let median = if n % 2 == 1 {
363            sorted[n / 2]
364        } else {
365            (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
366        };
367        let th = self.theme.as_ref();
368        let items = [
369            (mean, "μ", th.map_or(Color::White, |t| t.foreground), 0u16),
370            (
371                median,
372                "med",
373                th.map_or(Color::Yellow, |t| t.color(2)),
374                1u16,
375            ),
376        ];
377        for (v, name, color, row) in items {
378            let fx = ((v - x0) / (x1 - x0)).clamp(0.0, 1.0);
379            let x = plot.x + ((fx * span as f64) as u16).min(span - 1);
380            for y in plot.y..plot.bottom() {
381                if let Some(c) = buf.cell_mut((x, y)) {
382                    c.set_char('┆').set_fg(color);
383                }
384            }
385            let label = format!("{name} {}", format_tick(v, 0.1));
386            let lx = if x + 1 + label.chars().count() as u16 <= plot.right() {
387                x + 1
388            } else {
389                x.saturating_sub(label.chars().count() as u16)
390            };
391            crate::text::put_str(
392                buf,
393                lx,
394                plot.y + row,
395                plot.right(),
396                &label,
397                Style::default().fg(color),
398            );
399        }
400    }
401}
402
403impl Histogram {
404    fn render_into(&self, area: Rect, buf: &mut Buffer) {
405        let chart = self.to_bar_chart();
406        (&chart).render(area, buf);
407        if self.kde && !self.cumulative && self.orientation == BarOrientation::Vertical {
408            self.draw_kde(&chart, area, buf);
409        }
410        if self.stats && !self.cumulative && self.orientation == BarOrientation::Vertical {
411            self.draw_stats(&chart, area, buf);
412        }
413    }
414}
415
416widget_impls!(Histogram);
417
418#[cfg(feature = "theme")]
419impl tui_nuances::Themed for Histogram {
420    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
421        self.theme(theme)
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use ratatui::widgets::Widget;
429
430    #[test]
431    fn stats_draw_mean_and_median_labels() {
432        let area = Rect::new(0, 0, 50, 14);
433        let mut buf = Buffer::empty(area);
434        Histogram::new((0..200).map(|i| (i % 50) as f64))
435            .bins(10)
436            .stats(true)
437            .render(area, &mut buf);
438        let all: String = buf.content().iter().map(|c| c.symbol()).collect();
439        assert!(all.contains('┆') && all.contains('μ') && all.contains("med"));
440    }
441
442    #[test]
443    fn bins_cover_all_samples() {
444        let h = Histogram::new((0..100).map(|i| i as f64)).bins(10);
445        let b = h.compute_bins();
446        assert_eq!(b.len(), 10);
447        assert_eq!(b.iter().map(|b| b.count).sum::<usize>(), 100);
448        assert!(b.iter().all(|b| b.count == 10));
449    }
450
451    #[test]
452    fn max_value_in_last_bin() {
453        let b = Histogram::new([0.0, 10.0]).bins(2).compute_bins();
454        assert_eq!(b[0].count, 1);
455        assert_eq!(b[1].count, 1);
456    }
457
458    #[test]
459    fn sturges_default() {
460        let b = Histogram::new((0..64).map(|i| i as f64)).compute_bins();
461        assert_eq!(b.len(), 7);
462    }
463
464    #[test]
465    fn constant_data_ok() {
466        let b = Histogram::new([5.0; 4]).bins(3).compute_bins();
467        assert_eq!(b.iter().map(|b| b.count).sum::<usize>(), 4);
468    }
469
470    #[test]
471    fn empty_and_nan() {
472        assert!(Histogram::new([f64::NAN]).compute_bins().is_empty());
473        let area = Rect::new(0, 0, 20, 8);
474        let mut buf = Buffer::empty(area);
475        Histogram::new(Vec::<f64>::new()).render(area, &mut buf);
476    }
477
478    #[test]
479    fn explicit_range_drops_outliers() {
480        let b = Histogram::new([1.0, 2.0, 100.0])
481            .range(0.0, 10.0)
482            .bins(2)
483            .compute_bins();
484        assert_eq!(b.iter().map(|b| b.count).sum::<usize>(), 2);
485    }
486
487    #[test]
488    fn renders_bars() {
489        let area = Rect::new(0, 0, 40, 12);
490        let mut buf = Buffer::empty(area);
491        let data: Vec<f64> = (0..200).map(|i| ((i * 37) % 100) as f64).collect();
492        Histogram::new(data)
493            .bins(8)
494            .block(Block::bordered())
495            .render(area, &mut buf);
496        let t: String = (0..12)
497            .flat_map(|y| (0..40).map(move |x| (x, y)))
498            .map(|p| buf[p].symbol().to_string())
499            .collect();
500        assert!(t.contains('█'));
501    }
502
503    #[test]
504    fn horizontal_renders() {
505        let area = Rect::new(0, 0, 40, 12);
506        let mut buf = Buffer::empty(area);
507        Histogram::new((0..50).map(|i| i as f64))
508            .bins(5)
509            .orientation(BarOrientation::Horizontal)
510            .show_values(true)
511            .render(area, &mut buf);
512    }
513
514    #[test]
515    fn cumulative_ends_at_total() {
516        let h = Histogram::new((0..100).map(|i| i as f64)).bins(10);
517        let c = h.clone().cumulative(true).heights();
518        assert_eq!(*c.last().unwrap(), 100.0);
519        assert!(c.windows(2).all(|w| w[0] <= w[1]));
520        let n = h.cumulative(true).normalized(true).heights();
521        assert!((n.last().unwrap() - 1.0).abs() < 1e-9);
522    }
523
524    #[test]
525    fn density_integrates_to_one() {
526        let h = Histogram::new((0..100).map(|i| i as f64)).bins(10);
527        let w = h.compute_bins()[0].end - h.compute_bins()[0].start;
528        let s: f64 = h.normalized(true).heights().iter().map(|d| d * w).sum();
529        assert!((s - 1.0).abs() < 1e-9);
530    }
531
532    #[test]
533    fn kde_shape_and_degenerate() {
534        let h = Histogram::new((0..200).map(|i| ((i * 7) % 50) as f64));
535        let k = h.kde_curve(30, None);
536        assert_eq!(k.len(), 30);
537        assert!(k.iter().all(|p| p.1.is_finite() && p.1 >= 0.0));
538        assert!(Histogram::new(Vec::<f64>::new())
539            .kde_curve(10, None)
540            .is_empty());
541        assert!(Histogram::new([3.0; 5])
542            .kde_curve(5, None)
543            .iter()
544            .all(|p| p.1.is_finite()));
545    }
546}