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