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 key_fill(&self) -> Option<((u8, u8, u8), f64)> {
113        Some((self.fill, self.alpha))
114    }
115
116    fn draw(
117        &self,
118        data: &DataFrame,
119        coord: &dyn Coord,
120        scales: &ScaleSet,
121        _theme: &Theme,
122        backend: &mut dyn DrawBackend,
123    ) -> Result<(), RenderError> {
124        let x_col = data
125            .column("x")
126            .ok_or(RenderError::MissingAesthetic("x".into()))?;
127        let y_col = data
128            .column("y")
129            .ok_or(RenderError::MissingAesthetic("y".into()))?;
130        let fill_col = data.column("fill");
131        // A `label` (or the fill value) becomes each tile's hover tooltip.
132        let label_col = data.column("label").or(fill_col);
133        let date_key = data.column(crate::stat::calendar::DATE_KEY_COL);
134
135        let plot_area = backend.plot_area();
136        let x_scale = scales.get(&Aesthetic::X);
137        let y_scale = scales.get(&Aesthetic::Y);
138
139        // Continuous extents come from `setup_data` (resolution-sized).
140        let xmin_col = data.column("xmin");
141        let xmax_col = data.column("xmax");
142        let ymin_col = data.column("ymin");
143        let ymax_col = data.column("ymax");
144        let ext = |c: Option<&[crate::data::Value]>, i: usize, fallback: f64| {
145            c.and_then(|c| c[i].as_f64()).unwrap_or(fallback)
146        };
147        // Discrete axes (categorical heatmap): centre the tile on the category
148        // and size it to the break spacing; continuous axes use data ± half.
149        let x_disc = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
150        let y_disc = y_scale.map(|s| s.is_discrete()).unwrap_or(false);
151        let nbx = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
152        let nby = y_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
153
154        for i in 0..data.nrows() {
155            let (nxmin, nxmax) = if x_disc {
156                let nc = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
157                let hw = self.width / (nbx * 2.0);
158                (nc - hw, nc + hw)
159            } else {
160                let cx = x_col[i].as_f64().unwrap_or(0.0);
161                let (lo, hi) = (
162                    ext(xmin_col, i, cx - self.width / 2.0),
163                    ext(xmax_col, i, cx + self.width / 2.0),
164                );
165                (
166                    x_scale
167                        .map(|s| s.map(&crate::data::Value::Float(lo)))
168                        .unwrap_or(0.0),
169                    x_scale
170                        .map(|s| s.map(&crate::data::Value::Float(hi)))
171                        .unwrap_or(0.0),
172                )
173            };
174            let (nymin, nymax) = if y_disc {
175                let nc = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
176                let hh = self.height / (nby * 2.0);
177                (nc - hh, nc + hh)
178            } else {
179                let cy = y_col[i].as_f64().unwrap_or(0.0);
180                let (lo, hi) = (
181                    ext(ymin_col, i, cy - self.height / 2.0),
182                    ext(ymax_col, i, cy + self.height / 2.0),
183                );
184                (
185                    y_scale
186                        .map(|s| s.map(&crate::data::Value::Float(lo)))
187                        .unwrap_or(0.0),
188                    y_scale
189                        .map(|s| s.map(&crate::data::Value::Float(hi)))
190                        .unwrap_or(0.0),
191                )
192            };
193
194            let (left, top) = coord.transform((nxmin, nymax), &plot_area);
195            let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
196
197            let fill_color = fill_col
198                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
199                .unwrap_or(self.fill);
200            // #206: a no-data cell draws its scale's na_pattern instead
201            // of a flat na colour, when set.
202            let pattern = fill_col
203                .filter(|fc| matches!(fc[i], crate::data::Value::Na))
204                .and_then(|_| scales.na_fill_pattern(&Aesthetic::Fill));
205
206            // Hover tooltip: "x, y: value" — or "date: value" for calendar
207            // cells, whose x/y are layout positions.
208            let value = label_col
209                .map(|c| super::tip_value(&c[i]))
210                .filter(|s| !s.is_empty());
211            let raw = fill_col.and_then(|c| super::raw_value(&c[i]));
212            let x_raw_for_fmt = if let Some(key) = date_key.map(|c| super::tip_value(&c[i])) {
213                let tip = match value {
214                    Some(v) => format!("{key}: {v}"),
215                    None => key.clone(),
216                };
217                super::set_mark(backend, Some(tip), Some(key), None, raw.clone());
218                date_key.and_then(|c| c.get(i))
219            } else {
220                let xs = super::tip_value(&x_col[i]);
221                let ys = super::tip_value(&y_col[i]);
222                let tip = match value {
223                    Some(v) => format!("{xs}, {ys}: {v}"),
224                    None => format!("{xs}, {ys}"),
225                };
226                super::set_mark(backend, Some(tip), Some(xs), Some(ys), raw.clone());
227                Some(&x_col[i])
228            };
229            super::set_mark_formatted(
230                backend,
231                scales,
232                x_raw_for_fmt,
233                &Aesthetic::Fill,
234                fill_col.map(|c| &c[i]),
235            );
236            super::set_row_extras(backend, data, i);
237
238            let style = RectStyle {
239                fill: Some(fill_color),
240                stroke: Some(self.color),
241                stroke_width: self.line_width,
242                alpha: self.alpha,
243                clip: true,
244                corner_radius: self.radius,
245            };
246            match &pattern {
247                Some(p) => backend.draw_rect_pattern(
248                    (left, top.min(bottom)),
249                    (right, top.max(bottom)),
250                    p,
251                    &style,
252                )?,
253                None => {
254                    backend.draw_rect((left, top.min(bottom)), (right, top.max(bottom)), &style)?
255                }
256            }
257        }
258        super::clear_mark(backend);
259        super::clear_row_extras(backend);
260
261        Ok(())
262    }
263
264    fn required_aes(&self) -> Vec<Aesthetic> {
265        vec![Aesthetic::X, Aesthetic::Y]
266    }
267
268    fn default_stat(&self) -> Box<dyn Stat> {
269        Box::new(StatIdentity)
270    }
271
272    fn default_position(&self) -> Box<dyn Position> {
273        Box::new(PositionIdentity)
274    }
275
276    fn default_params(&self) -> GeomParams {
277        GeomParams::default()
278    }
279
280    fn name(&self) -> &str {
281        "tile"
282    }
283
284    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
285        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
286            self.color = ink;
287        }
288    }
289
290    fn consumes_tooltips(&self) -> bool {
291        true
292    }
293
294    fn setup_data(&self, data: &mut DataFrame, _warnings: &mut Vec<String>) {
295        add_extents(data, "x", "xmin", "xmax", self.width);
296        add_extents(data, "y", "ymin", "ymax", self.height);
297    }
298
299    fn set_series_color(&mut self, color: (u8, u8, u8)) {
300        self.fill = color;
301    }
302}