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