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 ratatui::{
6    buffer::Buffer,
7    layout::Rect,
8    style::{Color, Style},
9    widgets::Block,
10};
11
12/// One data series of a [`RadarChart`].
13#[derive(Debug, Clone)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct RadarSeries {
16    /// Series name.
17    pub name: String,
18    /// One value per axis.
19    pub values: Vec<f64>,
20    /// Optional series color (overrides the theme palette).
21    pub color: Option<Color>,
22}
23
24impl RadarSeries {
25    /// Create a series.
26    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
27        Self {
28            name: name.into(),
29            values: values.into_iter().collect(),
30            color: None,
31        }
32    }
33    opt_setter!(
34        /// Set color.
35        color: Color
36    );
37}
38
39/// Spider chart with N axes and any number of series.
40#[derive(Debug, Clone)]
41pub struct RadarChart<'a> {
42    axes: Vec<String>,
43    series: Vec<RadarSeries>,
44    max: Option<f64>,
45    rings: usize,
46    fill: bool,
47    show_labels: bool,
48    theme: Option<Theme>,
49    base: Option<Style>,
50    marker: Marker,
51    block: Option<Block<'a>>,
52}
53
54impl<'a> RadarChart<'a> {
55    /// Create a chart from axis labels.
56    pub fn new(axes: impl IntoIterator<Item = impl Into<String>>) -> Self {
57        Self {
58            axes: axes.into_iter().map(Into::into).collect(),
59            series: Vec::new(),
60            max: None,
61            rings: 4,
62            fill: false,
63            show_labels: true,
64            theme: None,
65            base: None,
66            marker: Marker::Braille,
67            block: None,
68        }
69    }
70    /// Add a series.
71    pub fn series(mut self, s: RadarSeries) -> Self {
72        self.series.push(s);
73        self
74    }
75    opt_setter!(
76        /// Fix the outer-ring value (default: largest data value).
77        max: f64
78    );
79    setter!(
80        /// Number of concentric rings.
81        rings: usize
82    );
83    setter!(
84        /// Fill the polygons instead of outlining.
85        fill: bool
86    );
87    setter!(
88        /// Show axis labels.
89        show_labels: bool
90    );
91    theme_setter!(
92        /// Apply a [`Theme`]: palette series colors, grid/label colors and
93        /// background fill. Explicit [`RadarSeries::color`] wins.
94        theme
95    );
96    base_style_setter!(base);
97    fn series_color(&self, i: usize, s: &RadarSeries) -> Color {
98        s.color
99            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.color(i)))
100    }
101    setter!(
102        /// Glyph family used for dot drawing (default [`Marker::Braille`]).
103        marker: Marker
104    );
105
106    block_setter!(block, 'a);
107
108    fn draw(&self, area: Rect, buf: &mut Buffer) {
109        let n = self.axes.len();
110        if n < 3 || area.width < 3 || area.height < 3 {
111            return;
112        }
113        let lab_w = self
114            .axes
115            .iter()
116            .map(|a| a.chars().count())
117            .max()
118            .unwrap_or(0) as u16;
119        let labels = self.show_labels && area.height >= 5 && area.width > 2 * lab_w + 4;
120        let (mx, my) = if labels { (lab_w, 1) } else { (0, 0) };
121        let plot = Rect::new(
122            area.x + mx,
123            area.y + my,
124            area.width - 2 * mx,
125            area.height - 2 * my,
126        );
127        let max = self
128            .max
129            .filter(|m| m.is_finite() && *m > 0.0)
130            .unwrap_or_else(|| {
131                let m = self
132                    .series
133                    .iter()
134                    .flat_map(|s| s.values.iter().copied())
135                    .filter(|v| v.is_finite())
136                    .fold(0.0, f64::max);
137                if m > 0.0 {
138                    m
139                } else {
140                    1.0
141                }
142            });
143        let mut cv = Canvas::new(plot.width, plot.height, self.marker);
144        let (pw, ph) = (cv.px_w() as f64, cv.px_h() as f64);
145        let r = ((pw - 1.0) / 2.0).min((ph - 1.0) / 2.0).max(1.0);
146        let (cx, cy) = ((pw - 1.0) / 2.0, (ph - 1.0) / 2.0);
147        let ang =
148            |i: usize| -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / n as f64;
149        let pt = |i: usize, rad: f64| {
150            (
151                (cx + rad * ang(i).cos()).round() as i32,
152                (cy + rad * ang(i).sin()).round() as i32,
153            )
154        };
155        let grid = self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid);
156        let fg = self.theme.as_ref().map_or(Color::White, |t| t.foreground);
157        for k in 1..=self.rings {
158            let rad = r * k as f64 / self.rings as f64;
159            for i in 0..n {
160                let (a, b) = (pt(i, rad), pt((i + 1) % n, rad));
161                cv.line(a.0, a.1, b.0, b.1, grid);
162            }
163        }
164        for i in 0..n {
165            let b = pt(i, r);
166            cv.line(cx.round() as i32, cy.round() as i32, b.0, b.1, grid);
167        }
168        for (si, s) in self.series.iter().enumerate() {
169            let color = self.series_color(si, s);
170            let pts: Vec<(i32, i32)> = (0..n)
171                .map(|i| {
172                    let v = s
173                        .values
174                        .get(i)
175                        .copied()
176                        .filter(|v| v.is_finite())
177                        .unwrap_or(0.0);
178                    pt(i, r * (v / max).clamp(0.0, 1.0))
179                })
180                .collect();
181            if self.fill {
182                for i in 0..n {
183                    let (a, b) = (pts[i], pts[(i + 1) % n]);
184                    let steps = (a.0 - b.0).abs().max((a.1 - b.1).abs()).max(1);
185                    for t in 0..=steps {
186                        let x = a.0 + (b.0 - a.0) * t / steps;
187                        let y = a.1 + (b.1 - a.1) * t / steps;
188                        cv.line(cx.round() as i32, cy.round() as i32, x, y, color);
189                    }
190                }
191            }
192            for i in 0..n {
193                let (a, b) = (pts[i], pts[(i + 1) % n]);
194                cv.line(a.0, a.1, b.0, b.1, color);
195            }
196        }
197        cv.render(buf, plot);
198        if labels {
199            for (i, l) in self.axes.iter().enumerate() {
200                let (ux, uy) = (ang(i).cos(), ang(i).sin());
201                let w = l.chars().count() as i32;
202                let ccx = plot.x as i32 + plot.width as i32 / 2;
203                let ccy = plot.y as i32 + plot.height as i32 / 2;
204                let ex = ccx + (ux * (plot.width as f64 / 2.0)).round() as i32;
205                let ey = ccy + (uy * (plot.height as f64 / 2.0 + 1.0)).round() as i32;
206                let x = if ux > 0.3 {
207                    ex
208                } else if ux < -0.3 {
209                    ex - w
210                } else {
211                    ex - w / 2
212                };
213                let y = ey.clamp(area.y as i32, area.bottom() as i32 - 1);
214                for (j, ch) in l.chars().enumerate() {
215                    let xx = x + j as i32;
216                    if xx >= area.x as i32 && xx < area.right() as i32 {
217                        if let Some(c) = buf.cell_mut((xx as u16, y as u16)) {
218                            c.set_char(ch).set_fg(fg);
219                        }
220                    }
221                }
222            }
223        }
224    }
225}
226
227impl RadarChart<'_> {
228    fn render_into(&self, area: Rect, buf: &mut Buffer) {
229        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
230        self.draw(inner, buf);
231    }
232}
233
234widget_impls!(RadarChart<'_>);
235
236#[cfg(feature = "theme")]
237impl<'a> tui_nuances::Themed for RadarChart<'a> {
238    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
239        self.theme(theme)
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use ratatui::widgets::Widget;
247
248    fn chart() -> RadarChart<'static> {
249        RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
250            .series(RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]).color(Color::Red))
251            .max(5.0)
252    }
253
254    fn run(c: RadarChart, w: u16, h: u16) -> Buffer {
255        let a = Rect::new(0, 0, w, h);
256        let mut b = Buffer::empty(a);
257        c.render(a, &mut b);
258        b
259    }
260
261    #[test]
262    fn draws_series_and_labels() {
263        let b = run(chart(), 40, 20);
264        assert!(b
265            .content()
266            .iter()
267            .any(|c| c.fg == Color::Red && c.symbol() != " "));
268        assert!(b
269            .content()
270            .iter()
271            .any(|c| c.fg == Color::DarkGray && c.symbol() != " "));
272        let t: String = b.content().iter().map(|c| c.symbol()).collect();
273        assert!(t.contains("Atk") && t.contains("Hp"));
274    }
275
276    #[cfg(feature = "theme")]
277    #[test]
278    fn theme_palette_and_override() {
279        let t = Theme::nord();
280        let mk = |c: Option<Color>| {
281            let s = RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]);
282            let s = if let Some(c) = c { s.color(c) } else { s };
283            RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
284                .series(s)
285                .series(RadarSeries::new("b", [1.0, 2.0, 3.0, 4.0, 5.0]))
286                .max(5.0)
287                .theme(&t)
288        };
289        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.fg == c && x.symbol() != " ");
290        let b = run(mk(None), 40, 20);
291        assert!(has(&b, t.color(0)) && has(&b, t.color(1)));
292        assert_eq!(b[(0, 0)].bg, t.background.unwrap());
293        let b = run(mk(Some(Color::Red)), 40, 20);
294        assert!(has(&b, Color::Red) && !has(&b, t.color(0)) && has(&b, t.color(1)));
295    }
296
297    #[test]
298    fn fill_covers_more_cells() {
299        let count = |b: &Buffer| b.content().iter().filter(|c| c.fg == Color::Red).count();
300        assert!(count(&run(chart().fill(true), 40, 20)) > count(&run(chart(), 40, 20)));
301    }
302
303    #[test]
304    fn degenerate_inputs() {
305        run(chart(), 0, 0);
306        run(chart(), 3, 3);
307        run(chart(), 5, 40);
308        run(RadarChart::new(["a"]), 20, 10);
309        run(
310            RadarChart::new(["a", "b", "c"])
311                .series(RadarSeries::new("n", [f64::NAN, -1.0]))
312                .rings(0),
313            20,
314            10,
315        );
316    }
317}