Skip to main content

tui_chart/
bubble.rs

1//! Bubble chart: scatter plot where each point has a size.
2
3use crate::PALETTE;
4use crate::canvas::{Canvas, Marker};
5use crate::text::put_str;
6use crate::theme::{self, Theme};
7use crate::util::{format_tick, nice_bounds, nice_ticks};
8use ratatui::{
9    buffer::Buffer,
10    layout::Rect,
11    style::{Color, Style},
12    widgets::Block,
13};
14
15/// A named set of `(x, y, size)` points.
16#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct BubbleSeries {
19    /// Series name.
20    pub name: String,
21    /// `(x, y, size)` points; non-finite points are skipped.
22    pub points: Vec<(f64, f64, f64)>,
23    /// Explicit color.
24    pub color: Option<Color>,
25}
26
27impl BubbleSeries {
28    /// Create a series.
29    pub fn new(name: impl Into<String>, points: impl IntoIterator<Item = (f64, f64, f64)>) -> Self {
30        Self {
31            name: name.into(),
32            points: points.into_iter().collect(),
33            color: None,
34        }
35    }
36
37    /// Explicit color.
38    pub fn color(mut self, c: Color) -> Self {
39        self.color = Some(c);
40        self
41    }
42}
43
44/// Bubble chart widget. Bubble area is proportional to size.
45///
46/// # Example
47///
48/// ```
49/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
50/// use tui_chart::{BubbleChart, BubbleSeries};
51///
52/// let chart = BubbleChart::new([BubbleSeries::new("a", [(1.0, 2.0, 5.0), (3.0, 1.0, 9.0)])]);
53/// let area = Rect::new(0, 0, 40, 12);
54/// let mut buf = Buffer::empty(area);
55/// chart.render(area, &mut buf);
56/// ```
57#[derive(Debug, Clone, Default)]
58pub struct BubbleChart {
59    series: Vec<BubbleSeries>,
60    max_radius: Option<u16>,
61    marker: Marker,
62    theme: Option<Theme>,
63    base: Option<Style>,
64    block: Option<Block<'static>>,
65}
66
67impl BubbleChart {
68    /// Create a bubble chart.
69    pub fn new(series: impl IntoIterator<Item = BubbleSeries>) -> Self {
70        Self {
71            series: series.into_iter().collect(),
72            ..Self::default()
73        }
74    }
75
76    opt_setter!(
77        /// Largest bubble radius in dots (default: a fraction of the plot size).
78        max_radius: u16
79    );
80
81    setter!(
82        /// Dot resolution (default braille).
83        marker: Marker
84    );
85
86    theme_setter!(
87        /// Apply a [`Theme`]; explicit series colors win.
88        theme
89    );
90
91    base_style_setter!(base);
92
93    block_setter!(block, 'static);
94
95    fn render_into(&self, area: Rect, buf: &mut Buffer) {
96        let area = area.intersection(buf.area);
97        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
98        if inner.width < 8 || inner.height < 4 {
99            return;
100        }
101        let pts = || {
102            self.series.iter().flat_map(|s| {
103                s.points
104                    .iter()
105                    .filter(|(x, y, z)| x.is_finite() && y.is_finite() && z.is_finite())
106            })
107        };
108        if pts().next().is_none() {
109            return;
110        }
111        let (mut x0, mut x1) = (f64::MAX, f64::MIN);
112        let (mut y0, mut y1) = (f64::MAX, f64::MIN);
113        let mut zmax = 0f64;
114        for &(x, y, z) in pts() {
115            x0 = x0.min(x);
116            x1 = x1.max(x);
117            y0 = y0.min(y);
118            y1 = y1.max(y);
119            zmax = zmax.max(z.abs());
120        }
121        let (x0, x1) = nice_bounds(x0, x1, 5);
122        let (y0, y1) = nice_bounds(y0, y1, 5);
123        let (xs, ys) = ((x1 - x0).max(f64::EPSILON), (y1 - y0).max(f64::EPSILON));
124        let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
125        let text = self
126            .theme
127            .as_ref()
128            .map_or(Style::default(), |t| t.label_style());
129
130        let yt = nice_ticks(y0, y1, (inner.height as usize / 3).max(2));
131        let ystep = if yt.len() >= 2 { yt[1] - yt[0] } else { 1.0 };
132        let ylabels: Vec<String> = yt.iter().map(|v| format_tick(*v, ystep)).collect();
133        let gutter = (ylabels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
134            .min(inner.width / 2);
135        let plot = Rect::new(
136            inner.x + gutter,
137            inner.y,
138            inner.width - gutter,
139            inner.height - 1,
140        );
141        if plot.width < 2 || plot.height < 2 {
142            return;
143        }
144        let mut cv = Canvas::new(plot.width, plot.height, self.marker);
145        let (pw, ph) = (cv.px_w(), cv.px_h());
146        let rmax = self
147            .max_radius
148            .map_or(((ph.min(pw / 2)) / 5).max(2), |r| r as i32);
149        // Keep whole bubbles inside the plot: map data into the inset area.
150        let (ix, iy) = (rmax.min(pw / 3), rmax.min(ph / 3));
151        let (aw, ah) = (
152            (pw - 1 - 2 * ix).max(1) as f64,
153            (ph - 1 - 2 * iy).max(1) as f64,
154        );
155        for (si, s) in self.series.iter().enumerate() {
156            let color = s.color.unwrap_or_else(|| {
157                self.theme
158                    .as_ref()
159                    .map_or(PALETTE[si % PALETTE.len()], |t| t.color(si))
160            });
161            for (pi, &(x, y, z)) in s.points.iter().enumerate() {
162                if !(x.is_finite() && y.is_finite() && z.is_finite()) {
163                    continue;
164                }
165                let cx = ix + ((x - x0) / xs * aw).round() as i32;
166                let cy = iy + ((1.0 - (y - y0) / ys) * ah).round() as i32;
167                let r = if zmax > 0.0 {
168                    ((z.abs() / zmax).sqrt() * rmax as f64).round() as i32
169                } else {
170                    0
171                }
172                .max(1);
173                if crate::interact::recording() {
174                    let (rx, ry) = self.marker.resolution();
175                    let (rx, ry) = (i32::from(rx), i32::from(ry));
176                    let (x_lo, x_hi) = ((cx - r).max(0) / rx, (cx + r).max(0) / rx);
177                    let (y_lo, y_hi) = ((cy - r).max(0) / ry, (cy + r).max(0) / ry);
178                    let rect = Rect::new(
179                        plot.x + x_lo as u16,
180                        plot.y + y_lo as u16,
181                        (x_hi - x_lo + 1) as u16,
182                        (y_hi - y_lo + 1) as u16,
183                    )
184                    .intersection(plot);
185                    crate::interact::record_point(rect, si, pi, || {
186                        let f = crate::util::format_compact;
187                        (
188                            s.name.clone(),
189                            vec![format!("x {}  y {}", f(x), f(y)), format!("size {}", f(z))],
190                        )
191                    });
192                }
193                for dy in -r..=r {
194                    for dx in -r..=r {
195                        // dots are not square on every marker; scale x by the aspect
196                        let (rx, ry) = self.marker.resolution();
197                        let ax = dx * ry as i32 / rx as i32;
198                        if ax * ax + dy * dy <= r * r {
199                            cv.set(cx + dx, cy + dy, color);
200                        }
201                    }
202                }
203            }
204        }
205        for (v, l) in yt.iter().zip(&ylabels) {
206            let f = ((v - y0) / ys).clamp(0.0, 1.0);
207            let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
208            let w = l.chars().count() as u16;
209            put_str(
210                buf,
211                inner.x + gutter.saturating_sub(w + 1),
212                y,
213                plot.x,
214                l,
215                dim,
216            );
217            for x in plot.x..plot.right() {
218                if buf[(x, y)].symbol() == " " {
219                    buf[(x, y)].set_char('┈').set_style(dim);
220                }
221            }
222        }
223        cv.render(buf, plot);
224        let xt = nice_ticks(x0, x1, (plot.width as usize / 10).max(2));
225        let xstep = if xt.len() >= 2 { xt[1] - xt[0] } else { 1.0 };
226        for v in xt {
227            let f = ((v - x0) / xs).clamp(0.0, 1.0);
228            let x = plot.x + (f * (plot.width - 1) as f64).round() as u16;
229            let l = format_tick(v, xstep);
230            let lx = x.saturating_sub(l.chars().count() as u16 / 2).max(plot.x);
231            put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
232        }
233    }
234}
235
236widget_impls!(BubbleChart);
237
238#[cfg(feature = "theme")]
239impl tui_nuances::Themed for BubbleChart {
240    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
241        self.theme(theme)
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use ratatui::widgets::Widget;
249
250    fn render(c: &BubbleChart, w: u16, h: u16) -> Buffer {
251        let a = Rect::new(0, 0, w, h);
252        let mut b = Buffer::empty(a);
253        c.render(a, &mut b);
254        b
255    }
256
257    #[test]
258    fn bigger_size_covers_more_cells() {
259        let count = |z: f64| {
260            let c =
261                BubbleChart::new([
262                    BubbleSeries::new("a", [(0.0, 0.0, 100.0), (10.0, 10.0, z)]).color(Color::Red)
263                ]);
264            render(&c, 60, 20)
265                .content()
266                .iter()
267                .filter(|c| c.fg == Color::Red && c.symbol() != " ")
268                .count()
269        };
270        assert!(count(100.0) > count(1.0));
271    }
272
273    #[test]
274    fn degenerate_inputs_do_not_panic() {
275        let c = BubbleChart::new([BubbleSeries::new(
276            "a",
277            [(f64::NAN, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -3.0)],
278        )]);
279        render(&c, 40, 12);
280        render(&c, 5, 3);
281        render(&c, 0, 0);
282        render(&BubbleChart::new([]), 40, 12);
283        render(
284            &BubbleChart::new([BubbleSeries::new("z", [(0.0, 0.0, 0.0)])]),
285            40,
286            12,
287        );
288    }
289
290    #[test]
291    fn max_radius_limits_size() {
292        let count = |r: u16| {
293            let c =
294                BubbleChart::new([
295                    BubbleSeries::new("a", [(0.0, 0.0, 10.0), (5.0, 5.0, 100.0)]).color(Color::Red),
296                ])
297                .max_radius(r);
298            render(&c, 60, 20)
299                .content()
300                .iter()
301                .filter(|c| c.fg == Color::Red && c.symbol() != " ")
302                .count()
303        };
304        assert!(count(8) > count(2));
305    }
306
307    #[test]
308    fn multiple_series_and_markers() {
309        for m in [Marker::Braille, Marker::HalfBlock, Marker::Dot] {
310            let c = BubbleChart::new([
311                BubbleSeries::new("a", [(1.0, 1.0, 5.0)]).color(Color::Red),
312                BubbleSeries::new("b", [(2.0, 3.0, 9.0)]).color(Color::Blue),
313            ])
314            .marker(m);
315            let b = render(&c, 50, 16);
316            assert!(b.content().iter().any(|x| x.fg == Color::Blue));
317        }
318    }
319}