Skip to main content

tui_chart/
radar.rs

1//! Radar (spider) chart drawn on a braille canvas.
2
3use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, Theme};
5use crate::util::darken;
6use ratatui::{
7    buffer::Buffer,
8    layout::Rect,
9    style::{Color, Style},
10    widgets::Block,
11};
12
13/// One data series of a [`RadarChart`].
14#[derive(Debug, Clone)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct RadarSeries {
17    /// Series name.
18    pub name: String,
19    /// One value per axis.
20    pub values: Vec<f64>,
21    /// Optional series color (overrides the theme palette).
22    pub color: Option<Color>,
23}
24
25impl RadarSeries {
26    /// Create a series.
27    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
28        Self {
29            name: name.into(),
30            values: values.into_iter().collect(),
31            color: None,
32        }
33    }
34    opt_setter!(
35        /// Set color.
36        color: Color
37    );
38}
39
40/// Spider chart with N axes and any number of series.
41///
42/// # Example
43///
44/// ```
45/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
46/// use tui_chart::{RadarChart, RadarSeries};
47///
48/// let chart = RadarChart::new(["Speed", "Power", "Armor"]).series(RadarSeries::new("A", [3.0, 7.0, 5.0]));
49/// let area = Rect::new(0, 0, 40, 12);
50/// let mut buf = Buffer::empty(area);
51/// chart.render(area, &mut buf);
52/// ```
53#[derive(Debug, Clone)]
54pub struct RadarChart<'a> {
55    axes: Vec<String>,
56    series: Vec<RadarSeries>,
57    max: Option<f64>,
58    rings: usize,
59    fill: bool,
60    show_labels: bool,
61    legend: bool,
62    hidden: Vec<usize>,
63    theme: Option<Theme>,
64    base: Option<Style>,
65    marker: Marker,
66    block: Option<Block<'a>>,
67}
68
69impl<'a> RadarChart<'a> {
70    /// Create a chart from axis labels.
71    pub fn new(axes: impl IntoIterator<Item = impl Into<String>>) -> Self {
72        Self {
73            axes: axes.into_iter().map(Into::into).collect(),
74            series: Vec::new(),
75            max: None,
76            rings: 4,
77            fill: false,
78            show_labels: true,
79            legend: true,
80            hidden: vec![],
81            theme: None,
82            base: None,
83            marker: Marker::Braille,
84            block: None,
85        }
86    }
87    /// Add a series.
88    pub fn series(mut self, s: RadarSeries) -> Self {
89        self.series.push(s);
90        self
91    }
92    opt_setter!(
93        /// Fix the outer-ring value (default: largest data value).
94        max: f64
95    );
96    setter!(
97        /// Number of concentric rings.
98        rings: usize
99    );
100    setter!(
101        /// Fill the polygons instead of outlining.
102        fill: bool
103    );
104    setter!(
105        /// Show axis labels.
106        show_labels: bool
107    );
108    theme_setter!(
109        /// Apply a [`Theme`]: palette series colors, grid/label colors and
110        /// background fill. Explicit [`RadarSeries::color`] wins.
111        theme
112    );
113    base_style_setter!(base);
114    fn series_color(&self, i: usize, s: &RadarSeries) -> Color {
115        s.color
116            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.color(i)))
117    }
118    setter!(
119        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
120        marker: Marker
121    );
122
123    setter!(
124        /// Series-name legend on the bottom row (default on, shown when it fits).
125        legend: bool
126    );
127
128    /// Hide series by index; they stay in the legend so they can be toggled
129    /// back, see [`Interaction`](crate::Interaction).
130    #[must_use]
131    pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
132        self.hidden = hidden.into_iter().collect();
133        self
134    }
135
136    block_setter!(block, 'a);
137
138    fn draw(&self, area: Rect, buf: &mut Buffer) {
139        let n = self.axes.len();
140        if n < 3 || area.width < 3 || area.height < 3 {
141            return;
142        }
143        let legend = self.legend && area.height >= 9 && !self.series.is_empty();
144        let full = area;
145        let area = if legend {
146            Rect::new(area.x, area.y, area.width, area.height - 1)
147        } else {
148            area
149        };
150        let lab_w = self
151            .axes
152            .iter()
153            .map(|a| a.chars().count())
154            .max()
155            .unwrap_or(0) as u16;
156        let labels = self.show_labels && area.height >= 5 && area.width > 2 * lab_w + 4;
157        let (mx, my) = if labels { (lab_w, 1) } else { (0, 0) };
158        let plot = Rect::new(
159            area.x + mx,
160            area.y + my,
161            area.width - 2 * mx,
162            area.height - 2 * my,
163        );
164        let max = self
165            .max
166            .filter(|m| m.is_finite() && *m > 0.0)
167            .unwrap_or_else(|| {
168                let m = self
169                    .series
170                    .iter()
171                    .flat_map(|s| s.values.iter().copied())
172                    .filter(|v| v.is_finite())
173                    .fold(0.0, f64::max);
174                if m > 0.0 {
175                    m
176                } else {
177                    1.0
178                }
179            });
180        let mut cv = Canvas::new(plot.width, plot.height, self.marker);
181        let (pw, ph) = (cv.px_w() as f64, cv.px_h() as f64);
182        let r = ((pw - 1.0) / 2.0).min((ph - 1.0) / 2.0).max(1.0);
183        let (cx, cy) = ((pw - 1.0) / 2.0, (ph - 1.0) / 2.0);
184        let ang =
185            |i: usize| -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / n as f64;
186        let pt = |i: usize, rad: f64| {
187            (
188                (cx + rad * ang(i).cos()).round() as i32,
189                (cy + rad * ang(i).sin()).round() as i32,
190            )
191        };
192        let grid = self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid);
193        let fg = self.theme.as_ref().map_or(Color::White, |t| t.foreground);
194        for k in 1..=self.rings {
195            let rad = r * k as f64 / self.rings as f64;
196            for i in 0..n {
197                let (a, b) = (pt(i, rad), pt((i + 1) % n, rad));
198                cv.line(a.0, a.1, b.0, b.1, grid);
199            }
200        }
201        for i in 0..n {
202            let b = pt(i, r);
203            cv.line(cx.round() as i32, cy.round() as i32, b.0, b.1, grid);
204        }
205        let mut polys: Vec<(Color, Vec<(i32, i32)>)> = vec![];
206        for (si, s) in self.series.iter().enumerate() {
207            if self.hidden.contains(&si) {
208                continue;
209            }
210            let color = self.series_color(si, s);
211            let pts: Vec<(i32, i32)> = (0..n)
212                .map(|i| {
213                    let v = s
214                        .values
215                        .get(i)
216                        .copied()
217                        .filter(|v| v.is_finite())
218                        .unwrap_or(0.0);
219                    pt(i, r * (v / max).clamp(0.0, 1.0))
220                })
221                .collect();
222            if crate::interact::recording() {
223                let (rx, ry) = self.marker.resolution();
224                for (i, &(x, y)) in pts.iter().enumerate() {
225                    let rect = Rect::new(
226                        plot.x + (x.max(0) / i32::from(rx)) as u16,
227                        plot.y + (y.max(0) / i32::from(ry)) as u16,
228                        1,
229                        1,
230                    )
231                    .intersection(plot);
232                    crate::interact::record_point(rect, si, i, || {
233                        let v = s.values.get(i).copied().unwrap_or(0.0);
234                        (
235                            s.name.clone(),
236                            vec![format!(
237                                "{}: {}",
238                                self.axes[i],
239                                crate::util::format_compact(v)
240                            )],
241                        )
242                    });
243                }
244            }
245            polys.push((color, pts));
246        }
247        if self.fill {
248            // scanline even-odd fill in a dimmed series color
249            for (color, pts) in &polys {
250                let dim = darken(*color, 0.55);
251                for py in 0..ph as i32 {
252                    let mut xs: Vec<f64> = vec![];
253                    for i in 0..n {
254                        let (a, b) = (pts[i], pts[(i + 1) % n]);
255                        let (y0, y1) = (a.1.min(b.1), a.1.max(b.1));
256                        if py >= y0 && py < y1 {
257                            let t = (py - a.1) as f64 / (b.1 - a.1) as f64;
258                            xs.push(a.0 as f64 + t * (b.0 - a.0) as f64);
259                        }
260                    }
261                    xs.sort_by(|a, b| a.total_cmp(b));
262                    for pair in xs.chunks(2) {
263                        if let [x0, x1] = pair {
264                            for px in x0.round() as i32..=x1.round() as i32 {
265                                cv.set(px, py, dim);
266                            }
267                        }
268                    }
269                }
270            }
271        }
272        for (color, pts) in &polys {
273            for i in 0..n {
274                let (a, b) = (pts[i], pts[(i + 1) % n]);
275                cv.line(a.0, a.1, b.0, b.1, *color);
276            }
277            for &(x, y) in pts {
278                for (dx, dy) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
279                    cv.set(x + dx, y + dy, *color);
280                }
281            }
282        }
283        cv.render(buf, plot);
284        // ring values along the first axis (up), dim
285        if self.rings > 0 && plot.height >= 9 {
286            let (rxd, ryd) = self.marker.resolution();
287            let dim = Style::default().fg(darken(fg, 0.4));
288            let ccx = plot.x as i32 + plot.width as i32 / 2;
289            let ccy = plot.y as i32 + plot.height as i32 / 2;
290            for k in 1..=self.rings {
291                let v = max * k as f64 / self.rings as f64;
292                let y = ccy - (r * k as f64 / self.rings as f64 / ryd as f64).round() as i32;
293                let _ = rxd;
294                let t = crate::util::format_tick(v, max / self.rings as f64);
295                if y > plot.y as i32 && y < plot.bottom() as i32 && ccx + 2 < plot.right() as i32 {
296                    crate::text::put_str(buf, (ccx + 2) as u16, y as u16, plot.right(), &t, dim);
297                }
298            }
299        }
300        if legend {
301            let mut x = full.x + 1;
302            let y = full.bottom() - 1;
303            for (si, se) in self.series.iter().enumerate() {
304                let c = self.series_color(si, se);
305                let name = format!(" {}", se.name);
306                if x + 2 + name.chars().count() as u16 > full.right() {
307                    break;
308                }
309                let off = self.hidden.contains(&si);
310                let name_style = if off {
311                    Style::default().fg(fg).add_modifier(
312                        ratatui::style::Modifier::CROSSED_OUT | ratatui::style::Modifier::DIM,
313                    )
314                } else {
315                    Style::default().fg(fg)
316                };
317                crate::text::put_str(
318                    buf,
319                    x,
320                    y,
321                    full.right(),
322                    if off { "○" } else { "●" },
323                    Style::default().fg(c),
324                );
325                crate::text::put_str(buf, x + 1, y, full.right(), &name, name_style);
326                crate::interact::record_legend(
327                    Rect::new(x, y, 2 + name.chars().count() as u16, 1),
328                    si,
329                    &se.name,
330                );
331                x += 3 + name.chars().count() as u16;
332            }
333        }
334        if labels {
335            for (i, l) in self.axes.iter().enumerate() {
336                let (ux, uy) = (ang(i).cos(), ang(i).sin());
337                let w = l.chars().count() as i32;
338                let ccx = plot.x as i32 + plot.width as i32 / 2;
339                let ccy = plot.y as i32 + plot.height as i32 / 2;
340                let (rxd, ryd) = self.marker.resolution();
341                let (rx, ry) = (r / rxd as f64, r / ryd as f64);
342                let ex = ccx + (ux * (rx + 1.5)).round() as i32;
343                let ey = ccy + (uy * (ry + 1.0)).round() as i32;
344                let x = if ux > 0.3 {
345                    ex
346                } else if ux < -0.3 {
347                    ex - w
348                } else {
349                    ex - w / 2
350                };
351                let y = ey.clamp(area.y as i32, area.bottom() as i32 - 1);
352                for (j, ch) in l.chars().enumerate() {
353                    let xx = x + j as i32;
354                    if xx >= area.x as i32 && xx < area.right() as i32 {
355                        if let Some(c) = buf.cell_mut((xx as u16, y as u16)) {
356                            c.set_char(ch).set_fg(fg);
357                        }
358                    }
359                }
360            }
361        }
362    }
363}
364
365impl RadarChart<'_> {
366    fn render_into(&self, area: Rect, buf: &mut Buffer) {
367        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
368        self.draw(inner, buf);
369    }
370}
371
372widget_impls!(RadarChart<'_>);
373
374#[cfg(feature = "theme")]
375impl<'a> tui_nuances::Themed for RadarChart<'a> {
376    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
377        self.theme(theme)
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use ratatui::widgets::Widget;
385
386    fn chart() -> RadarChart<'static> {
387        RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
388            .series(RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]).color(Color::Red))
389            .max(5.0)
390    }
391
392    fn run(c: RadarChart, w: u16, h: u16) -> Buffer {
393        let a = Rect::new(0, 0, w, h);
394        let mut b = Buffer::empty(a);
395        c.render(a, &mut b);
396        b
397    }
398
399    #[test]
400    fn draws_series_and_labels() {
401        let b = run(chart(), 40, 20);
402        assert!(b
403            .content()
404            .iter()
405            .any(|c| c.fg == Color::Red && c.symbol() != " "));
406        assert!(b
407            .content()
408            .iter()
409            .any(|c| c.fg == Color::DarkGray && c.symbol() != " "));
410        let t: String = b.content().iter().map(|c| c.symbol()).collect();
411        assert!(t.contains("Atk") && t.contains("Hp"));
412    }
413
414    #[cfg(feature = "theme")]
415    #[test]
416    fn theme_palette_and_override() {
417        let t = Theme::nord();
418        let mk = |c: Option<Color>| {
419            let s = RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]);
420            let s = if let Some(c) = c { s.color(c) } else { s };
421            RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
422                .series(s)
423                .series(RadarSeries::new("b", [1.0, 2.0, 3.0, 4.0, 5.0]))
424                .max(5.0)
425                .theme(&t)
426        };
427        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.fg == c && x.symbol() != " ");
428        let b = run(mk(None), 40, 20);
429        assert!(has(&b, t.color(0)) && has(&b, t.color(1)));
430        assert_eq!(b[(0, 0)].bg, t.background.unwrap());
431        let b = run(mk(Some(Color::Red)), 40, 20);
432        assert!(has(&b, Color::Red) && !has(&b, t.color(0)) && has(&b, t.color(1)));
433    }
434
435    #[test]
436    fn fill_covers_more_cells() {
437        let count = |b: &Buffer| {
438            b.content()
439                .iter()
440                .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::White)
441                .count()
442        };
443        assert!(count(&run(chart().fill(true), 40, 20)) > count(&run(chart(), 40, 20)));
444    }
445
446    #[test]
447    fn degenerate_inputs() {
448        run(chart(), 0, 0);
449        run(chart(), 3, 3);
450        run(chart(), 5, 40);
451        run(RadarChart::new(["a"]), 20, 10);
452        run(
453            RadarChart::new(["a", "b", "c"])
454                .series(RadarSeries::new("n", [f64::NAN, -1.0]))
455                .rings(0),
456            20,
457            10,
458        );
459    }
460}