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#[derive(Debug, Clone, Default)]
107pub struct Heatmap {
108    data: Vec<Vec<f64>>,
109    row_labels: Vec<String>,
110    col_labels: Vec<String>,
111    gradient: Option<Gradient>,
112    theme: Option<Theme>,
113    style: Option<Style>,
114    cell_width: u16,
115    cell_height: u16,
116    bounds: Option<(f64, f64)>,
117    show_values: bool,
118    legend: bool,
119    block: Option<Block<'static>>,
120}
121
122impl Heatmap {
123    /// Create from rows of values.
124    pub fn new(data: Vec<Vec<f64>>) -> Self {
125        Self {
126            data,
127            cell_width: 2,
128            cell_height: 1,
129            legend: true,
130            ..Default::default()
131        }
132    }
133
134    /// Row labels (left).
135    pub fn row_labels<I, S>(mut self, l: I) -> Self
136    where
137        I: IntoIterator<Item = S>,
138        S: Into<String>,
139    {
140        self.row_labels = l.into_iter().map(Into::into).collect();
141        self
142    }
143
144    /// Column labels (bottom).
145    pub fn col_labels<I, S>(mut self, l: I) -> Self
146    where
147        I: IntoIterator<Item = S>,
148        S: Into<String>,
149    {
150        self.col_labels = l.into_iter().map(Into::into).collect();
151        self
152    }
153
154    opt_setter!(
155        /// Color gradient.
156        gradient: Gradient
157    );
158
159    theme_setter!(
160        /// Apply a [`Theme`]: gradient derived from its accent/palette (unless
161        /// [`Heatmap::gradient`] was set), label colors and background fill.
162        theme
163    );
164
165    base_style_setter!(style);
166
167    fn grad(&self) -> Gradient {
168        match (&self.gradient, &self.theme) {
169            (Some(g), _) => g.clone(),
170            (None, Some(t)) => t.gradient(),
171            _ => Gradient::default(),
172        }
173    }
174
175    fn label_color(&self) -> Color {
176        self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
177    }
178
179    fn dim_color(&self) -> Color {
180        self.theme.as_ref().map_or(Color::DarkGray, |t| t.axis)
181    }
182
183    /// Cell width in columns (default 2).
184    pub fn cell_width(mut self, w: u16) -> Self {
185        self.cell_width = w.max(1);
186        self
187    }
188
189    /// Cell height in rows (default 1).
190    pub fn cell_height(mut self, h: u16) -> Self {
191        self.cell_height = h.max(1);
192        self
193    }
194
195    /// Fixed `(min, max)` color scale.
196    pub fn bounds(mut self, min: f64, max: f64) -> Self {
197        self.bounds = Some((min, max));
198        self
199    }
200
201    setter!(
202        /// Print values in cells when they fit.
203        show_values: bool
204    );
205
206    setter!(
207        /// Show the min–max gradient legend row.
208        legend: bool
209    );
210
211    block_setter!(block, 'static);
212
213    /// Resolved `(min, max)` of the color scale.
214    pub fn scale(&self) -> (f64, f64) {
215        if let Some(b) = self.bounds {
216            return b;
217        }
218        let vals = self.data.iter().flatten().filter(|v| v.is_finite());
219        let lo = vals.clone().cloned().fold(f64::INFINITY, f64::min);
220        let hi = vals.cloned().fold(f64::NEG_INFINITY, f64::max);
221        if lo.is_finite() {
222            (lo, hi)
223        } else {
224            (0.0, 1.0)
225        }
226    }
227
228    fn render_inner(&self, area: Rect, buf: &mut Buffer) {
229        let mut inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
230        let grad = self.grad();
231        let (lo, hi) = self.scale();
232        let span = if hi > lo { hi - lo } else { 1.0 };
233        if self.legend && inner.height > 4 {
234            let y = inner.bottom() - 1;
235            let (a, b) = (format_compact(lo), format_compact(hi));
236            let (aw, bw) = (text_width(&a), text_width(&b));
237            let lab = Style::default().fg(self.label_color());
238            let bx = inner.right().saturating_sub(bw).max(inner.x);
239            buf.set_stringn(inner.x, y, &a, inner.width as usize, lab);
240            buf.set_stringn(bx, y, &b, (inner.right() - bx) as usize, lab);
241            let bar_x = inner.x + aw + 1;
242            let bar_end = inner.right().saturating_sub(bw + 1);
243            if bar_end > bar_x {
244                let n = (bar_end - bar_x) as f64;
245                for (i, x) in (bar_x..bar_end).enumerate() {
246                    let c = grad.color_at(i as f64 / (n - 1.0).max(1.0));
247                    buf.set_string(x, y, " ", Style::default().bg(c));
248                }
249            }
250            inner.height -= 1;
251        }
252        let yw = self
253            .row_labels
254            .iter()
255            .map(|l| text_width(l))
256            .max()
257            .unwrap_or(0)
258            .min(12);
259        let Some(a) = layout::compute(inner, yw, !self.col_labels.is_empty(), false, false) else {
260            return;
261        };
262        let plot = a.plot;
263        let (cw, ch) = (self.cell_width, self.cell_height);
264        let mut y_ticks = vec![];
265        let mut x_ticks = vec![];
266        for (r, row) in self.data.iter().enumerate() {
267            let y = plot.y as u32 + r as u32 * ch as u32;
268            if y + ch as u32 > plot.bottom() as u32 {
269                break;
270            }
271            let y = y as u16;
272            if let Some(l) = self.row_labels.get(r) {
273                y_ticks.push((
274                    y - plot.y + ch / 2,
275                    l.chars().take(yw as usize).collect::<String>(),
276                ));
277            }
278            for (c, &v) in row.iter().enumerate() {
279                let x = plot.x as u32 + c as u32 * cw as u32;
280                if x + cw as u32 > plot.right() as u32 {
281                    break;
282                }
283                let x = x as u16;
284                if r == 0 {
285                    if let Some(l) = self.col_labels.get(c) {
286                        x_ticks.push((x - plot.x + cw / 2, l.clone()));
287                    }
288                }
289                let color = if v.is_finite() {
290                    grad.color_at((v - lo) / span)
291                } else {
292                    self.dim_color()
293                };
294                let fg = if luminance(color) > 140.0 {
295                    Color::Black
296                } else {
297                    Color::White
298                };
299                let text = if self.show_values && v.is_finite() {
300                    let s = format_compact(v);
301                    if text_width(&s) <= cw {
302                        s
303                    } else {
304                        String::new()
305                    }
306                } else {
307                    String::new()
308                };
309                for dy in 0..ch {
310                    for dx in 0..cw {
311                        buf.set_string(x + dx, y + dy, " ", Style::default().bg(color));
312                    }
313                }
314                if !text.is_empty() {
315                    let tx = x + (cw - text_width(&text)) / 2;
316                    buf.set_string(tx, y + ch / 2, &text, Style::default().bg(color).fg(fg));
317                }
318            }
319        }
320        layout::draw_axes(
321            buf,
322            &a,
323            Style::default().fg(self.dim_color()),
324            Style::default().fg(self.dim_color()),
325        );
326        let lab = Style::default().fg(self.label_color());
327        layout::draw_y_labels(buf, a.y_labels, &y_ticks, lab);
328        layout::draw_x_labels(buf, a.x_labels, &x_ticks, lab);
329    }
330}
331
332impl Heatmap {
333    fn render_into(&self, area: Rect, buf: &mut Buffer) {
334        self.render_inner(area, buf);
335    }
336}
337
338widget_impls!(Heatmap);
339
340#[cfg(feature = "theme")]
341impl tui_nuances::Themed for Heatmap {
342    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
343        self.theme(theme)
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use ratatui::widgets::Widget;
351
352    fn grid() -> Vec<Vec<f64>> {
353        (0..4)
354            .map(|r| (0..6).map(|c| (r * 6 + c) as f64).collect())
355            .collect()
356    }
357
358    #[test]
359    fn gradient_endpoints() {
360        assert_eq!(Gradient::Grayscale.color_at(0.0), Color::Rgb(0, 0, 0));
361        assert_eq!(Gradient::Grayscale.color_at(1.0), Color::Rgb(255, 255, 255));
362        assert_eq!(Gradient::Grayscale.color_at(0.5), Color::Rgb(128, 128, 128));
363        assert_eq!(Gradient::Grayscale.color_at(f64::NAN), Color::Rgb(0, 0, 0));
364        assert_eq!(Gradient::Grayscale.color_at(9.0), Color::Rgb(255, 255, 255));
365    }
366
367    #[test]
368    fn gradient_custom_and_cycle() {
369        let g = Gradient::Custom(vec![(0, 0, 0), (100, 0, 0), (200, 0, 0)]);
370        assert_eq!(g.color_at(0.5), Color::Rgb(100, 0, 0));
371        assert_eq!(
372            Gradient::Custom(vec![]).color_at(1.0),
373            Color::Rgb(255, 255, 255)
374        );
375        let mut g = Gradient::Viridis;
376        for _ in 0..5 {
377            g = g.next();
378        }
379        assert_eq!(g, Gradient::Viridis);
380        assert_eq!(Gradient::Heat.name(), "heat");
381    }
382
383    #[test]
384    fn scale_auto_and_fixed() {
385        assert_eq!(Heatmap::new(grid()).scale(), (0.0, 23.0));
386        assert_eq!(Heatmap::new(grid()).bounds(-1.0, 1.0).scale(), (-1.0, 1.0));
387        assert_eq!(Heatmap::new(vec![]).scale(), (0.0, 1.0));
388    }
389
390    #[test]
391    fn renders_colored_cells_and_labels() {
392        let area = Rect::new(0, 0, 40, 10);
393        let mut buf = Buffer::empty(area);
394        Heatmap::new(grid())
395            .row_labels(["a", "b", "c", "d"])
396            .col_labels(["1", "2", "3", "4", "5", "6"])
397            .gradient(Gradient::Grayscale)
398            .render(area, &mut buf);
399        // first data cell is darkest, last is brightest
400        let first = buf[(2, 0)].bg;
401        let last = buf[(2 + 5 * 2, 3)].bg;
402        assert_eq!(first, Color::Rgb(0, 0, 0));
403        assert_eq!(last, Color::Rgb(255, 255, 255));
404        assert_eq!(buf[(0, 0)].symbol(), "a");
405    }
406
407    #[test]
408    fn legend_row_drawn() {
409        let area = Rect::new(0, 0, 40, 10);
410        let mut buf = Buffer::empty(area);
411        Heatmap::new(grid()).render(area, &mut buf);
412        assert_eq!(buf[(0, 9)].symbol(), "0");
413        assert_eq!(buf[(39, 9)].symbol(), "3");
414        let mut buf2 = Buffer::empty(area);
415        Heatmap::new(grid()).legend(false).render(area, &mut buf2);
416        assert_eq!(buf2[(0, 9)].symbol(), "└");
417    }
418
419    #[test]
420    fn show_values_when_fit() {
421        let area = Rect::new(0, 0, 40, 10);
422        let mut buf = Buffer::empty(area);
423        Heatmap::new(vec![vec![7.0, 123456.0]])
424            .cell_width(3)
425            .show_values(true)
426            .render(area, &mut buf);
427        let t: String = (0..40).map(|x| buf[(x, 0)].symbol().to_string()).collect();
428        assert!(t.contains('7'));
429        assert!(!t.contains("123"));
430    }
431
432    #[test]
433    fn nan_cell_is_gray() {
434        let area = Rect::new(0, 0, 20, 8);
435        let mut buf = Buffer::empty(area);
436        Heatmap::new(vec![vec![f64::NAN, 1.0]])
437            .legend(false)
438            .render(area, &mut buf);
439        assert_eq!(buf[(1, 0)].bg, Color::DarkGray);
440    }
441
442    #[test]
443    fn tiny_safe() {
444        for (w, h) in [(0, 0), (2, 2), (6, 5)] {
445            let area = Rect::new(0, 0, w, h);
446            let mut buf = Buffer::empty(area);
447            Heatmap::new(grid())
448                .col_labels(["x"])
449                .render(area, &mut buf);
450        }
451    }
452}