Skip to main content

ggplot_rs/geom/
tile.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::identity::StatIdentity;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Tile geometry — rectangle centered at (x, y).
16///
17/// On a continuous axis a tile spans `width` × the data *resolution* (the
18/// smallest gap between distinct x values, like ggplot2's `resolution()`;
19/// `1` when there is a single value), so tiles on a 10-unit grid are 10 wide
20/// and abut. Their extents (`xmin`/`xmax`/`ymin`/`ymax`) train the position
21/// scales, so edge tiles stay inside the panel without manual expansion. On a
22/// discrete axis a tile fills `width` × its category slot.
23pub struct GeomTile {
24    pub fill: (u8, u8, u8),
25    pub color: (u8, u8, u8),
26    pub alpha: f64,
27    /// Tile width as a multiple of the x resolution (default 1 = abutting).
28    pub width: f64,
29    /// Tile height as a multiple of the y resolution (default 1 = abutting).
30    pub height: f64,
31    pub line_width: f64,
32    /// Corner radius in px (ggplot2 `geom_label(label.r)`, ggchicklet
33    /// `radius`, #176). `0.0` (the default) is a plain rectangle, unchanged
34    /// from pre-#176 behaviour.
35    pub radius: f64,
36}
37
38/// ggplot2's `resolution(x, zero = FALSE)`: the smallest gap between distinct
39/// finite values, or 1 when there are fewer than two.
40pub(crate) fn resolution(values: &[crate::data::Value]) -> f64 {
41    let mut xs: Vec<f64> = values
42        .iter()
43        .filter_map(|v| v.as_f64())
44        .filter(|f| f.is_finite())
45        .collect();
46    xs.sort_by(|a, b| a.total_cmp(b));
47    xs.dedup_by(|a, b| (*a - *b).abs() <= 1e-9 * a.abs().max(1.0));
48    let gap = xs
49        .windows(2)
50        .map(|w| w[1] - w[0])
51        .fold(f64::INFINITY, f64::min);
52    if gap.is_finite() && gap > 0.0 {
53        gap
54    } else {
55        1.0
56    }
57}
58
59/// Add `lo`/`hi` extent columns `centre ± mult·resolution/2` for a numeric
60/// column (skipped for discrete data or when the extents already exist).
61pub(crate) fn add_extents(data: &mut DataFrame, centre: &str, lo: &str, hi: &str, mult: f64) {
62    if data.has_column(lo) || data.has_column(hi) {
63        return;
64    }
65    let Some(col) = data.column(centre) else {
66        return;
67    };
68    if col
69        .iter()
70        .any(|v| matches!(v, crate::data::Value::Str(_) | crate::data::Value::Bool(_)))
71    {
72        return;
73    }
74    let half = mult * resolution(col) / 2.0;
75    let (los, his): (Vec<_>, Vec<_>) = col
76        .iter()
77        .map(|v| match v.as_f64() {
78            Some(c) => (
79                crate::data::Value::Float(c - half),
80                crate::data::Value::Float(c + half),
81            ),
82            None => (crate::data::Value::Na, crate::data::Value::Na),
83        })
84        .unzip();
85    data.add_column(lo.to_string(), los);
86    data.add_column(hi.to_string(), his);
87}
88
89impl Default for GeomTile {
90    fn default() -> Self {
91        GeomTile {
92            fill: (97, 156, 255),
93            color: (50, 50, 50),
94            alpha: 1.0,
95            width: 1.0,
96            height: 1.0,
97            line_width: 0.5,
98            radius: 0.0,
99        }
100    }
101}
102
103impl GeomTile {
104    /// Corner radius in px (#176). See the [`radius`](Self::radius) field doc.
105    pub fn with_radius(mut self, radius_px: f64) -> Self {
106        self.radius = radius_px;
107        self
108    }
109}
110
111impl Geom for GeomTile {
112    fn draw(
113        &self,
114        data: &DataFrame,
115        coord: &dyn Coord,
116        scales: &ScaleSet,
117        _theme: &Theme,
118        backend: &mut dyn DrawBackend,
119    ) -> Result<(), RenderError> {
120        let x_col = data
121            .column("x")
122            .ok_or(RenderError::MissingAesthetic("x".into()))?;
123        let y_col = data
124            .column("y")
125            .ok_or(RenderError::MissingAesthetic("y".into()))?;
126        let fill_col = data.column("fill");
127        // A `label` (or the fill value) becomes each tile's hover tooltip.
128        let label_col = data.column("label").or(fill_col);
129        let date_key = data.column(crate::stat::calendar::DATE_KEY_COL);
130
131        let plot_area = backend.plot_area();
132        let x_scale = scales.get(&Aesthetic::X);
133        let y_scale = scales.get(&Aesthetic::Y);
134
135        // Continuous extents come from `setup_data` (resolution-sized).
136        let xmin_col = data.column("xmin");
137        let xmax_col = data.column("xmax");
138        let ymin_col = data.column("ymin");
139        let ymax_col = data.column("ymax");
140        let ext = |c: Option<&[crate::data::Value]>, i: usize, fallback: f64| {
141            c.and_then(|c| c[i].as_f64()).unwrap_or(fallback)
142        };
143        // Discrete axes (categorical heatmap): centre the tile on the category
144        // and size it to the break spacing; continuous axes use data ± half.
145        let x_disc = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
146        let y_disc = y_scale.map(|s| s.is_discrete()).unwrap_or(false);
147        let nbx = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
148        let nby = y_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
149
150        for i in 0..data.nrows() {
151            let (nxmin, nxmax) = if x_disc {
152                let nc = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
153                let hw = self.width / (nbx * 2.0);
154                (nc - hw, nc + hw)
155            } else {
156                let cx = x_col[i].as_f64().unwrap_or(0.0);
157                let (lo, hi) = (
158                    ext(xmin_col, i, cx - self.width / 2.0),
159                    ext(xmax_col, i, cx + self.width / 2.0),
160                );
161                (
162                    x_scale
163                        .map(|s| s.map(&crate::data::Value::Float(lo)))
164                        .unwrap_or(0.0),
165                    x_scale
166                        .map(|s| s.map(&crate::data::Value::Float(hi)))
167                        .unwrap_or(0.0),
168                )
169            };
170            let (nymin, nymax) = if y_disc {
171                let nc = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
172                let hh = self.height / (nby * 2.0);
173                (nc - hh, nc + hh)
174            } else {
175                let cy = y_col[i].as_f64().unwrap_or(0.0);
176                let (lo, hi) = (
177                    ext(ymin_col, i, cy - self.height / 2.0),
178                    ext(ymax_col, i, cy + self.height / 2.0),
179                );
180                (
181                    y_scale
182                        .map(|s| s.map(&crate::data::Value::Float(lo)))
183                        .unwrap_or(0.0),
184                    y_scale
185                        .map(|s| s.map(&crate::data::Value::Float(hi)))
186                        .unwrap_or(0.0),
187                )
188            };
189
190            let (left, top) = coord.transform((nxmin, nymax), &plot_area);
191            let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
192
193            let fill_color = fill_col
194                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
195                .unwrap_or(self.fill);
196            // #206: a no-data cell draws its scale's na_pattern instead
197            // of a flat na colour, when set.
198            let pattern = fill_col
199                .filter(|fc| matches!(fc[i], crate::data::Value::Na))
200                .and_then(|_| scales.na_fill_pattern(&Aesthetic::Fill));
201
202            // Hover tooltip: "x, y: value" — or "date: value" for calendar
203            // cells, whose x/y are layout positions.
204            let value = label_col
205                .map(|c| super::tip_value(&c[i]))
206                .filter(|s| !s.is_empty());
207            let raw = fill_col.and_then(|c| super::raw_value(&c[i]));
208            let x_raw_for_fmt = if let Some(key) = date_key.map(|c| super::tip_value(&c[i])) {
209                let tip = match value {
210                    Some(v) => format!("{key}: {v}"),
211                    None => key.clone(),
212                };
213                super::set_mark(backend, Some(tip), Some(key), None, raw.clone());
214                date_key.and_then(|c| c.get(i))
215            } else {
216                let xs = super::tip_value(&x_col[i]);
217                let ys = super::tip_value(&y_col[i]);
218                let tip = match value {
219                    Some(v) => format!("{xs}, {ys}: {v}"),
220                    None => format!("{xs}, {ys}"),
221                };
222                super::set_mark(backend, Some(tip), Some(xs), Some(ys), raw.clone());
223                Some(&x_col[i])
224            };
225            super::set_mark_formatted(
226                backend,
227                scales,
228                x_raw_for_fmt,
229                &Aesthetic::Fill,
230                fill_col.map(|c| &c[i]),
231            );
232            super::set_row_extras(backend, data, i);
233
234            let style = RectStyle {
235                fill: Some(fill_color),
236                stroke: Some(self.color),
237                stroke_width: self.line_width,
238                alpha: self.alpha,
239                clip: true,
240                corner_radius: self.radius,
241            };
242            match &pattern {
243                Some(p) => backend.draw_rect_pattern(
244                    (left, top.min(bottom)),
245                    (right, top.max(bottom)),
246                    p,
247                    &style,
248                )?,
249                None => {
250                    backend.draw_rect((left, top.min(bottom)), (right, top.max(bottom)), &style)?
251                }
252            }
253        }
254        super::clear_mark(backend);
255        super::clear_row_extras(backend);
256
257        Ok(())
258    }
259
260    fn required_aes(&self) -> Vec<Aesthetic> {
261        vec![Aesthetic::X, Aesthetic::Y]
262    }
263
264    fn default_stat(&self) -> Box<dyn Stat> {
265        Box::new(StatIdentity)
266    }
267
268    fn default_position(&self) -> Box<dyn Position> {
269        Box::new(PositionIdentity)
270    }
271
272    fn default_params(&self) -> GeomParams {
273        GeomParams::default()
274    }
275
276    fn name(&self) -> &str {
277        "tile"
278    }
279
280    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
281        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
282            self.color = ink;
283        }
284    }
285
286    fn consumes_tooltips(&self) -> bool {
287        true
288    }
289
290    fn setup_data(&self, data: &mut DataFrame, _warnings: &mut Vec<String>) {
291        add_extents(data, "x", "xmin", "xmax", self.width);
292        add_extents(data, "y", "ymin", "ymax", self.height);
293    }
294
295    fn set_series_color(&mut self, color: (u8, u8, u8)) {
296        self.fill = color;
297    }
298}