Skip to main content

tui_chart/
heatmap.rs

1//! Heatmap with selectable color gradients.
2
3use crate::layout::{self, text_width};
4use crate::theme::{self, ChartThemeExt, Theme};
5use crate::util::format_compact;
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// Color gradient presets.
14#[derive(Debug, Clone, PartialEq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum Gradient {
17    /// Perceptual purple → teal → yellow.
18    #[default]
19    Viridis,
20    /// Black → red → yellow → white.
21    Heat,
22    /// Dark blue → cyan → white.
23    Cool,
24    /// Blue → white → red (diverging).
25    RedBlue,
26    /// Black → white.
27    Grayscale,
28    /// Custom RGB stops (evenly spaced, at least 2).
29    Custom(Vec<(u8, u8, u8)>),
30}
31
32impl Gradient {
33    fn stops(&self) -> Vec<(u8, u8, u8)> {
34        match self {
35            Gradient::Viridis => vec![
36                (68, 1, 84),
37                (59, 82, 139),
38                (33, 145, 140),
39                (94, 201, 98),
40                (253, 231, 37),
41            ],
42            Gradient::Heat => vec![
43                (0, 0, 0),
44                (180, 0, 0),
45                (255, 140, 0),
46                (255, 255, 80),
47                (255, 255, 255),
48            ],
49            Gradient::Cool => vec![
50                (10, 20, 80),
51                (30, 100, 200),
52                (60, 200, 230),
53                (255, 255, 255),
54            ],
55            Gradient::RedBlue => vec![(30, 60, 200), (255, 255, 255), (200, 30, 30)],
56            Gradient::Grayscale => vec![(0, 0, 0), (255, 255, 255)],
57            Gradient::Custom(s) if s.len() >= 2 => s.clone(),
58            Gradient::Custom(_) => vec![(0, 0, 0), (255, 255, 255)],
59        }
60    }
61
62    /// Color for `t` in `0..=1` (clamped; NaN → 0).
63    pub fn color_at(&self, t: f64) -> Color {
64        let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
65        let stops = self.stops();
66        let pos = t * (stops.len() - 1) as f64;
67        let i = (pos.floor() as usize).min(stops.len() - 2);
68        let f = pos - i as f64;
69        let (a, b) = (stops[i], stops[i + 1]);
70        let (r, g, bl) = crate::scale::mix_rgb(a, b, f);
71        Color::Rgb(r, g, bl)
72    }
73
74    /// Next preset (for cycling in demos).
75    pub fn next(&self) -> Gradient {
76        match self {
77            Gradient::Viridis => Gradient::Heat,
78            Gradient::Heat => Gradient::Cool,
79            Gradient::Cool => Gradient::RedBlue,
80            Gradient::RedBlue => Gradient::Grayscale,
81            _ => Gradient::Viridis,
82        }
83    }
84
85    /// Preset name.
86    pub fn name(&self) -> &'static str {
87        match self {
88            Gradient::Viridis => "viridis",
89            Gradient::Heat => "heat",
90            Gradient::Cool => "cool",
91            Gradient::RedBlue => "red-blue",
92            Gradient::Grayscale => "grayscale",
93            Gradient::Custom(_) => "custom",
94        }
95    }
96}
97
98fn luminance(c: Color) -> f64 {
99    match c {
100        Color::Rgb(r, g, b) => 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64,
101        _ => 128.0,
102    }
103}
104
105/// Heatmap widget (rows × columns of values).
106///
107/// # Example
108///
109/// ```
110/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
111/// use tui_chart::{Heatmap};
112///
113/// let chart = Heatmap::new(vec![vec![0.0, 0.5, 1.0], vec![1.0, 0.5, 0.0]]);
114/// let area = Rect::new(0, 0, 40, 12);
115/// let mut buf = Buffer::empty(area);
116/// chart.render(area, &mut buf);
117/// ```
118#[derive(Debug, Clone, Default)]
119pub struct Heatmap {
120    data: Vec<Vec<f64>>,
121    row_labels: Vec<String>,
122    col_labels: Vec<String>,
123    gradient: Option<Gradient>,
124    theme: Option<Theme>,
125    style: Option<Style>,
126    cell_width: u16,
127    cell_height: u16,
128    bounds: Option<(f64, f64)>,
129    show_values: bool,
130    stretch: bool,
131    legend: bool,
132    block: Option<Block<'static>>,
133}
134
135impl Heatmap {
136    /// Create from rows of values.
137    pub fn new(data: Vec<Vec<f64>>) -> Self {
138        Self {
139            data,
140            cell_width: 2,
141            cell_height: 1,
142            legend: true,
143            ..Default::default()
144        }
145    }
146
147    /// Row labels (left).
148    pub fn row_labels<I, S>(mut self, l: I) -> Self
149    where
150        I: IntoIterator<Item = S>,
151        S: Into<String>,
152    {
153        self.row_labels = l.into_iter().map(Into::into).collect();
154        self
155    }
156
157    /// Column labels (bottom).
158    pub fn col_labels<I, S>(mut self, l: I) -> Self
159    where
160        I: IntoIterator<Item = S>,
161        S: Into<String>,
162    {
163        self.col_labels = l.into_iter().map(Into::into).collect();
164        self
165    }
166
167    opt_setter!(
168        /// Color gradient.
169        gradient: Gradient
170    );
171
172    theme_setter!(
173        /// Apply a [`Theme`]: gradient derived from its accent/palette (unless
174        /// [`Heatmap::gradient`] was set), label colors and background fill.
175        theme
176    );
177
178    base_style_setter!(style);
179
180    fn grad(&self) -> Gradient {
181        match (&self.gradient, &self.theme) {
182            (Some(g), _) => g.clone(),
183            (None, Some(t)) => t.gradient(),
184            _ => Gradient::default(),
185        }
186    }
187
188    fn label_color(&self) -> Color {
189        self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
190    }
191
192    fn dim_color(&self) -> Color {
193        self.theme.as_ref().map_or(Color::DarkGray, |t| t.axis)
194    }
195
196    /// Cell width in columns (default 2).
197    pub fn cell_width(mut self, w: u16) -> Self {
198        self.cell_width = w.max(1);
199        self
200    }
201
202    /// Cell height in rows (default 1).
203    pub fn cell_height(mut self, h: u16) -> Self {
204        self.cell_height = h.max(1);
205        self
206    }
207
208    /// Fixed `(min, max)` color scale.
209    pub fn bounds(mut self, min: f64, max: f64) -> Self {
210        self.bounds = Some((min, max));
211        self
212    }
213
214    setter!(
215        /// Print values in cells when they fit.
216        show_values: bool
217    );
218
219    setter!(
220        /// Stretch cells so the grid fills the plot area (overrides
221        /// [`cell_width`](Self::cell_width) / [`cell_height`](Self::cell_height)).
222        stretch: bool
223    );
224
225    setter!(
226        /// Show the min–max gradient legend row.
227        legend: bool
228    );
229
230    block_setter!(block, 'static);
231
232    /// Resolved `(min, max)` of the color scale.
233    pub fn scale(&self) -> (f64, f64) {
234        if let Some(b) = self.bounds {
235            return b;
236        }
237        let vals = self.data.iter().flatten().filter(|v| v.is_finite());
238        let lo = vals.clone().cloned().fold(f64::INFINITY, f64::min);
239        let hi = vals.cloned().fold(f64::NEG_INFINITY, f64::max);
240        if lo.is_finite() {
241            (lo, hi)
242        } else {
243            (0.0, 1.0)
244        }
245    }
246
247    fn render_inner(&self, area: Rect, buf: &mut Buffer) {
248        let mut inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
249        let grad = self.grad();
250        let (lo, hi) = self.scale();
251        let span = if hi > lo { hi - lo } else { 1.0 };
252        if self.legend && inner.height > 4 {
253            let y = inner.bottom() - 1;
254            let (a, b) = (format_compact(lo), format_compact(hi));
255            let (aw, bw) = (text_width(&a), text_width(&b));
256            let lab = Style::default().fg(self.label_color());
257            let bx = inner.right().saturating_sub(bw).max(inner.x);
258            buf.set_stringn(inner.x, y, &a, inner.width as usize, lab);
259            buf.set_stringn(bx, y, &b, (inner.right() - bx) as usize, lab);
260            let bar_x = inner.x + aw + 1;
261            let bar_end = inner.right().saturating_sub(bw + 1);
262            if bar_end > bar_x {
263                let n = (bar_end - bar_x) as f64;
264                for (i, x) in (bar_x..bar_end).enumerate() {
265                    let c = grad.color_at(i as f64 / (n - 1.0).max(1.0));
266                    buf.set_string(x, y, " ", Style::default().bg(c));
267                }
268            }
269            inner.height -= 1;
270        }
271        let yw = self
272            .row_labels
273            .iter()
274            .map(|l| text_width(l))
275            .max()
276            .unwrap_or(0)
277            .min(12);
278        let Some(a) = layout::compute(inner, yw, !self.col_labels.is_empty(), false, false) else {
279            return;
280        };
281        let plot = a.plot;
282        let cols = self.data.iter().map(Vec::len).max().unwrap_or(1).max(1);
283        let rows = self.data.len().max(1);
284        // (offset, size) of a cell span: fixed stride, or proportional when stretched
285        let span_of = |i: usize, n: usize, total: u16, fixed: u16| -> (u16, u16) {
286            if self.stretch && n as u16 <= total {
287                let a = i * total as usize / n;
288                let b = (i + 1) * total as usize / n;
289                (a as u16, (b - a).max(1) as u16)
290            } else {
291                ((i as u32 * fixed as u32).min(u16::MAX as u32) as u16, fixed)
292            }
293        };
294        let mut y_ticks = vec![];
295        let mut x_ticks = vec![];
296        for (r, row) in self.data.iter().enumerate() {
297            let (dy0, ch) = span_of(r, rows, plot.height, self.cell_height);
298            let y = plot.y as u32 + dy0 as u32;
299            if y + ch as u32 > plot.bottom() as u32 {
300                break;
301            }
302            let y = y as u16;
303            if let Some(l) = self.row_labels.get(r) {
304                y_ticks.push((
305                    y - plot.y + ch / 2,
306                    l.chars().take(yw as usize).collect::<String>(),
307                ));
308            }
309            for (c, &v) in row.iter().enumerate() {
310                let (dx0, cw) = span_of(c, cols, plot.width, self.cell_width);
311                let x = plot.x as u32 + dx0 as u32;
312                if x + cw as u32 > plot.right() as u32 {
313                    break;
314                }
315                let x = x as u16;
316                if r == 0 {
317                    if let Some(l) = self.col_labels.get(c) {
318                        x_ticks.push((x - plot.x + cw / 2, l.clone()));
319                    }
320                }
321                let color = if v.is_finite() {
322                    grad.color_at((v - lo) / span)
323                } else {
324                    self.dim_color()
325                };
326                let fg = if luminance(color) > 140.0 {
327                    Color::Black
328                } else {
329                    Color::White
330                };
331                let text = if self.show_values && v.is_finite() {
332                    let s = format_compact(v);
333                    if text_width(&s) <= cw {
334                        s
335                    } else {
336                        String::new()
337                    }
338                } else {
339                    String::new()
340                };
341                for dy in 0..ch {
342                    for dx in 0..cw {
343                        buf.set_string(x + dx, y + dy, " ", Style::default().bg(color));
344                    }
345                }
346                if !text.is_empty() {
347                    let tx = x + (cw - text_width(&text)) / 2;
348                    buf.set_string(tx, y + ch / 2, &text, Style::default().bg(color).fg(fg));
349                }
350            }
351        }
352        layout::draw_axes(
353            buf,
354            &a,
355            Style::default().fg(self.dim_color()),
356            Style::default().fg(self.dim_color()),
357        );
358        let lab = Style::default().fg(self.label_color());
359        layout::draw_y_labels(buf, a.y_labels, &y_ticks, lab);
360        layout::draw_x_labels(buf, a.x_labels, &x_ticks, lab);
361    }
362}
363
364impl Heatmap {
365    fn render_into(&self, area: Rect, buf: &mut Buffer) {
366        self.render_inner(area, buf);
367    }
368}
369
370widget_impls!(Heatmap);
371
372#[cfg(feature = "theme")]
373impl tui_nuances::Themed for Heatmap {
374    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
375        self.theme(theme)
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use ratatui::widgets::Widget;
383
384    fn grid() -> Vec<Vec<f64>> {
385        (0..4)
386            .map(|r| (0..6).map(|c| (r * 6 + c) as f64).collect())
387            .collect()
388    }
389
390    #[test]
391    fn gradient_endpoints() {
392        assert_eq!(Gradient::Grayscale.color_at(0.0), Color::Rgb(0, 0, 0));
393        assert_eq!(Gradient::Grayscale.color_at(1.0), Color::Rgb(255, 255, 255));
394        assert_eq!(Gradient::Grayscale.color_at(0.5), Color::Rgb(128, 128, 128));
395        assert_eq!(Gradient::Grayscale.color_at(f64::NAN), Color::Rgb(0, 0, 0));
396        assert_eq!(Gradient::Grayscale.color_at(9.0), Color::Rgb(255, 255, 255));
397    }
398
399    #[test]
400    fn gradient_custom_and_cycle() {
401        let g = Gradient::Custom(vec![(0, 0, 0), (100, 0, 0), (200, 0, 0)]);
402        assert_eq!(g.color_at(0.5), Color::Rgb(100, 0, 0));
403        assert_eq!(
404            Gradient::Custom(vec![]).color_at(1.0),
405            Color::Rgb(255, 255, 255)
406        );
407        let mut g = Gradient::Viridis;
408        for _ in 0..5 {
409            g = g.next();
410        }
411        assert_eq!(g, Gradient::Viridis);
412        assert_eq!(Gradient::Heat.name(), "heat");
413    }
414
415    #[test]
416    fn scale_auto_and_fixed() {
417        assert_eq!(Heatmap::new(grid()).scale(), (0.0, 23.0));
418        assert_eq!(Heatmap::new(grid()).bounds(-1.0, 1.0).scale(), (-1.0, 1.0));
419        assert_eq!(Heatmap::new(vec![]).scale(), (0.0, 1.0));
420    }
421
422    #[test]
423    fn renders_colored_cells_and_labels() {
424        let area = Rect::new(0, 0, 40, 10);
425        let mut buf = Buffer::empty(area);
426        Heatmap::new(grid())
427            .row_labels(["a", "b", "c", "d"])
428            .col_labels(["1", "2", "3", "4", "5", "6"])
429            .gradient(Gradient::Grayscale)
430            .render(area, &mut buf);
431        // first data cell is darkest, last is brightest
432        let first = buf[(2, 0)].bg;
433        let last = buf[(2 + 5 * 2, 3)].bg;
434        assert_eq!(first, Color::Rgb(0, 0, 0));
435        assert_eq!(last, Color::Rgb(255, 255, 255));
436        assert_eq!(buf[(0, 0)].symbol(), "a");
437    }
438
439    #[test]
440    fn stretch_fills_plot() {
441        let area = Rect::new(0, 0, 40, 12);
442        let mut buf = Buffer::empty(area);
443        Heatmap::new(grid())
444            .stretch(true)
445            .legend(false)
446            .render(area, &mut buf);
447        let filled = |y: u16| (0..40).any(|x| buf[(x, y)].bg != Color::Reset);
448        assert!(filled(0) && filled(10), "grid should span the height");
449    }
450
451    #[test]
452    fn legend_row_drawn() {
453        let area = Rect::new(0, 0, 40, 10);
454        let mut buf = Buffer::empty(area);
455        Heatmap::new(grid()).render(area, &mut buf);
456        assert_eq!(buf[(0, 9)].symbol(), "0");
457        assert_eq!(buf[(39, 9)].symbol(), "3");
458        let mut buf2 = Buffer::empty(area);
459        Heatmap::new(grid()).legend(false).render(area, &mut buf2);
460        assert_eq!(buf2[(0, 9)].symbol(), "└");
461    }
462
463    #[test]
464    fn show_values_when_fit() {
465        let area = Rect::new(0, 0, 40, 10);
466        let mut buf = Buffer::empty(area);
467        Heatmap::new(vec![vec![7.0, 123456.0]])
468            .cell_width(3)
469            .show_values(true)
470            .render(area, &mut buf);
471        let t: String = (0..40).map(|x| buf[(x, 0)].symbol().to_string()).collect();
472        assert!(t.contains('7'));
473        assert!(!t.contains("123"));
474    }
475
476    #[test]
477    fn nan_cell_is_gray() {
478        let area = Rect::new(0, 0, 20, 8);
479        let mut buf = Buffer::empty(area);
480        Heatmap::new(vec![vec![f64::NAN, 1.0]])
481            .legend(false)
482            .render(area, &mut buf);
483        assert_eq!(buf[(1, 0)].bg, Color::DarkGray);
484    }
485
486    #[test]
487    fn tiny_safe() {
488        for (w, h) in [(0, 0), (2, 2), (6, 5)] {
489            let area = Rect::new(0, 0, w, h);
490            let mut buf = Buffer::empty(area);
491            Heatmap::new(grid())
492                .col_labels(["x"])
493                .render(area, &mut buf);
494        }
495    }
496}