Skip to main content

ggplot_rs/geom/
pack.rs

1//! Packed bubble chart: `geom_packed_bubble`. Circles with area ∝ `weight`
2//! packed without overlap, optionally clustered by `subgroup` (each cluster
3//! outlined). Layout by [`StatPack`].
4
5use crate::aes::Aesthetic;
6use crate::coord::Coord;
7use crate::data::{DataFrame, Value};
8use crate::position::identity::PositionIdentity;
9use crate::position::Position;
10use crate::render::backend::{DrawBackend, FontFace, PointStyle, TextAnchor, TextStyle};
11use crate::render::RenderError;
12use crate::scale::ScaleSet;
13use crate::stat::pack::StatPack;
14use crate::stat::Stat;
15use crate::theme::Theme;
16
17use super::treemap::{contrast_text, fit_size};
18use super::{Geom, GeomParams};
19
20/// Packed bubble chart. Map `weight` (area), optionally `subgroup`
21/// (clusters), `fill` and `label`.
22pub struct GeomPackedBubble {
23    pub sort: bool,
24    /// Gap between bubbles as a fraction of the mean radius.
25    pub padding: f64,
26    /// Fill when `fill` is unmapped.
27    pub fill: (u8, u8, u8),
28    pub alpha: f64,
29    /// Cluster outline colour (`None` hides it).
30    pub group_outline: Option<(u8, u8, u8)>,
31    pub label_size: f64,
32    pub min_label_size: f64,
33}
34
35impl Default for GeomPackedBubble {
36    fn default() -> Self {
37        GeomPackedBubble {
38            sort: true,
39            padding: 0.08,
40            fill: (97, 156, 255),
41            alpha: 0.9,
42            group_outline: Some((170, 170, 170)),
43            label_size: 10.0,
44            min_label_size: 6.0,
45        }
46    }
47}
48
49impl Geom for GeomPackedBubble {
50    fn draw(
51        &self,
52        data: &DataFrame,
53        coord: &dyn Coord,
54        scales: &ScaleSet,
55        theme: &Theme,
56        backend: &mut dyn DrawBackend,
57    ) -> Result<(), RenderError> {
58        let col = |n: &str| {
59            data.column(n)
60                .ok_or_else(|| RenderError::MissingAesthetic(n.into()))
61        };
62        let (part, xc, yc, rc) = (col("part")?, col("x")?, col("y")?, col("r")?);
63        let (fill_col, label_col, weight_col) = (
64            data.column("fill"),
65            data.column("label"),
66            data.column("weight"),
67        );
68        let area = backend.plot_area();
69        let px = |x: f64, y: f64| {
70            let sx = scales.get(&Aesthetic::X).map(|s| s.map(&Value::Float(x)));
71            let sy = scales.get(&Aesthetic::Y).map(|s| s.map(&Value::Float(y)));
72            coord.transform((sx.unwrap_or(0.5), sy.unwrap_or(0.5)), &area)
73        };
74        let radius_px = |x: f64, y: f64, r: f64| {
75            let c = px(x, y);
76            let (a, b) = (px(x + r, y), px(x, y + r));
77            (a.0 - c.0)
78                .hypot(a.1 - c.1)
79                .min((b.0 - c.0).hypot(b.1 - c.1))
80        };
81        let family = super::resolve_font_family("", theme);
82        let mut labels = Vec::new();
83
84        let mut order: Vec<usize> = (0..data.nrows()).collect();
85        // Cluster outlines under the bubbles.
86        order.sort_by_key(|&i| part[i].key_str() != "group");
87        for i in order {
88            let (Some(x), Some(y), Some(r)) = (xc[i].as_f64(), yc[i].as_f64(), rc[i].as_f64())
89            else {
90                continue;
91            };
92            let c = px(x, y);
93            let rp = radius_px(x, y, r);
94            if part[i].key_str() == "group" {
95                if let Some(outline) = self.group_outline {
96                    super::clear_mark(backend);
97                    backend.draw_circle(
98                        c,
99                        rp,
100                        &PointStyle {
101                            color: outline,
102                            alpha: 1.0,
103                            filled: false,
104                            ..Default::default()
105                        },
106                    )?;
107                }
108                continue;
109            }
110            let fill = fill_col
111                .and_then(|f| scales.map_color(&Aesthetic::Fill, &f[i]))
112                .unwrap_or(self.fill);
113            let label = label_col
114                .map(|l| super::tip_value(&l[i]))
115                .filter(|s| !s.is_empty());
116            let value = weight_col.map(|w| super::tip_value(&w[i]));
117            let tip = match (&label, &value) {
118                (Some(l), Some(v)) => format!("{l}: {v}"),
119                (Some(l), None) => l.clone(),
120                (None, Some(v)) => v.clone(),
121                (None, None) => String::new(),
122            };
123            super::set_mark(
124                backend,
125                (!tip.is_empty()).then_some(tip),
126                label.clone(),
127                super::series_key(data, i),
128                weight_col.and_then(|w| super::raw_value(&w[i])),
129            );
130            super::set_row_extras(backend, data, i);
131            backend.draw_circle(
132                c,
133                rp,
134                &PointStyle {
135                    color: fill,
136                    alpha: self.alpha,
137                    filled: true,
138                    ..Default::default()
139                },
140            )?;
141            if let Some(l) = label {
142                let side = rp * std::f64::consts::SQRT_2;
143                if let Some(size) = fit_size(&l, side, side, self.label_size, self.min_label_size) {
144                    labels.push((l, c, size, contrast_text(fill)));
145                }
146            }
147        }
148        super::clear_mark(backend);
149        super::clear_row_extras(backend);
150        for (text, pos, size, color) in labels {
151            backend.draw_text(
152                &text,
153                pos,
154                &TextStyle {
155                    color,
156                    size,
157                    anchor: TextAnchor::Middle,
158                    angle: 0.0,
159                    family: family.clone(),
160                    face: FontFace::Plain,
161                    bg_colour: None,
162                    bg_r: 0.0,
163                },
164            )?;
165        }
166        Ok(())
167    }
168
169    fn required_aes(&self) -> Vec<Aesthetic> {
170        Vec::new()
171    }
172
173    fn default_stat(&self) -> Box<dyn Stat> {
174        Box::new(StatPack {
175            sort: self.sort,
176            padding: self.padding,
177        })
178    }
179
180    fn default_position(&self) -> Box<dyn Position> {
181        Box::new(PositionIdentity)
182    }
183
184    fn default_params(&self) -> GeomParams {
185        GeomParams::default()
186    }
187
188    fn name(&self) -> &str {
189        "packed_bubble"
190    }
191
192    fn consumes_tooltips(&self) -> bool {
193        true
194    }
195
196    fn set_series_color(&mut self, color: (u8, u8, u8)) {
197        self.fill = color;
198    }
199}