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