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}
33
34/// ggplot2's `resolution(x, zero = FALSE)`: the smallest gap between distinct
35/// finite values, or 1 when there are fewer than two.
36pub(crate) fn resolution(values: &[crate::data::Value]) -> f64 {
37    let mut xs: Vec<f64> = values
38        .iter()
39        .filter_map(|v| v.as_f64())
40        .filter(|f| f.is_finite())
41        .collect();
42    xs.sort_by(|a, b| a.total_cmp(b));
43    xs.dedup_by(|a, b| (*a - *b).abs() <= 1e-9 * a.abs().max(1.0));
44    let gap = xs
45        .windows(2)
46        .map(|w| w[1] - w[0])
47        .fold(f64::INFINITY, f64::min);
48    if gap.is_finite() && gap > 0.0 {
49        gap
50    } else {
51        1.0
52    }
53}
54
55/// Add `lo`/`hi` extent columns `centre ± mult·resolution/2` for a numeric
56/// column (skipped for discrete data or when the extents already exist).
57pub(crate) fn add_extents(data: &mut DataFrame, centre: &str, lo: &str, hi: &str, mult: f64) {
58    if data.has_column(lo) || data.has_column(hi) {
59        return;
60    }
61    let Some(col) = data.column(centre) else {
62        return;
63    };
64    if col
65        .iter()
66        .any(|v| matches!(v, crate::data::Value::Str(_) | crate::data::Value::Bool(_)))
67    {
68        return;
69    }
70    let half = mult * resolution(col) / 2.0;
71    let (los, his): (Vec<_>, Vec<_>) = col
72        .iter()
73        .map(|v| match v.as_f64() {
74            Some(c) => (
75                crate::data::Value::Float(c - half),
76                crate::data::Value::Float(c + half),
77            ),
78            None => (crate::data::Value::Na, crate::data::Value::Na),
79        })
80        .unzip();
81    data.add_column(lo.to_string(), los);
82    data.add_column(hi.to_string(), his);
83}
84
85impl Default for GeomTile {
86    fn default() -> Self {
87        GeomTile {
88            fill: (97, 156, 255),
89            color: (50, 50, 50),
90            alpha: 1.0,
91            width: 1.0,
92            height: 1.0,
93            line_width: 0.5,
94        }
95    }
96}
97
98impl Geom for GeomTile {
99    fn draw(
100        &self,
101        data: &DataFrame,
102        coord: &dyn Coord,
103        scales: &ScaleSet,
104        _theme: &Theme,
105        backend: &mut dyn DrawBackend,
106    ) -> Result<(), RenderError> {
107        let x_col = data
108            .column("x")
109            .ok_or(RenderError::MissingAesthetic("x".into()))?;
110        let y_col = data
111            .column("y")
112            .ok_or(RenderError::MissingAesthetic("y".into()))?;
113        let fill_col = data.column("fill");
114        // A `label` (or the fill value) becomes each tile's hover tooltip.
115        let label_col = data.column("label").or(fill_col);
116        let date_key = data.column(crate::stat::calendar::DATE_KEY_COL);
117
118        let plot_area = backend.plot_area();
119        let x_scale = scales.get(&Aesthetic::X);
120        let y_scale = scales.get(&Aesthetic::Y);
121
122        // Continuous extents come from `setup_data` (resolution-sized).
123        let xmin_col = data.column("xmin");
124        let xmax_col = data.column("xmax");
125        let ymin_col = data.column("ymin");
126        let ymax_col = data.column("ymax");
127        let ext = |c: Option<&[crate::data::Value]>, i: usize, fallback: f64| {
128            c.and_then(|c| c[i].as_f64()).unwrap_or(fallback)
129        };
130        // Discrete axes (categorical heatmap): centre the tile on the category
131        // and size it to the break spacing; continuous axes use data ± half.
132        let x_disc = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
133        let y_disc = y_scale.map(|s| s.is_discrete()).unwrap_or(false);
134        let nbx = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
135        let nby = y_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
136
137        for i in 0..data.nrows() {
138            let (nxmin, nxmax) = if x_disc {
139                let nc = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
140                let hw = self.width / (nbx * 2.0);
141                (nc - hw, nc + hw)
142            } else {
143                let cx = x_col[i].as_f64().unwrap_or(0.0);
144                let (lo, hi) = (
145                    ext(xmin_col, i, cx - self.width / 2.0),
146                    ext(xmax_col, i, cx + self.width / 2.0),
147                );
148                (
149                    x_scale
150                        .map(|s| s.map(&crate::data::Value::Float(lo)))
151                        .unwrap_or(0.0),
152                    x_scale
153                        .map(|s| s.map(&crate::data::Value::Float(hi)))
154                        .unwrap_or(0.0),
155                )
156            };
157            let (nymin, nymax) = if y_disc {
158                let nc = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
159                let hh = self.height / (nby * 2.0);
160                (nc - hh, nc + hh)
161            } else {
162                let cy = y_col[i].as_f64().unwrap_or(0.0);
163                let (lo, hi) = (
164                    ext(ymin_col, i, cy - self.height / 2.0),
165                    ext(ymax_col, i, cy + self.height / 2.0),
166                );
167                (
168                    y_scale
169                        .map(|s| s.map(&crate::data::Value::Float(lo)))
170                        .unwrap_or(0.0),
171                    y_scale
172                        .map(|s| s.map(&crate::data::Value::Float(hi)))
173                        .unwrap_or(0.0),
174                )
175            };
176
177            let (left, top) = coord.transform((nxmin, nymax), &plot_area);
178            let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
179
180            let fill_color = fill_col
181                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
182                .unwrap_or(self.fill);
183
184            // Hover tooltip: "x, y: value" — or "date: value" for calendar
185            // cells, whose x/y are layout positions.
186            let value = label_col
187                .map(|c| super::tip_value(&c[i]))
188                .filter(|s| !s.is_empty());
189            let raw = fill_col.and_then(|c| super::raw_value(&c[i]));
190            if let Some(key) = date_key.map(|c| super::tip_value(&c[i])) {
191                let tip = match value {
192                    Some(v) => format!("{key}: {v}"),
193                    None => key.clone(),
194                };
195                super::set_mark(backend, Some(tip), Some(key), None, raw);
196            } else {
197                let xs = super::tip_value(&x_col[i]);
198                let ys = super::tip_value(&y_col[i]);
199                let tip = match value {
200                    Some(v) => format!("{xs}, {ys}: {v}"),
201                    None => format!("{xs}, {ys}"),
202                };
203                super::set_mark(backend, Some(tip), Some(xs), Some(ys), raw);
204            }
205
206            backend.draw_rect(
207                (left, top.min(bottom)),
208                (right, top.max(bottom)),
209                &RectStyle {
210                    fill: Some(fill_color),
211                    stroke: Some(self.color),
212                    stroke_width: self.line_width,
213                    alpha: self.alpha,
214                    clip: true,
215                },
216            )?;
217        }
218        super::clear_mark(backend);
219
220        Ok(())
221    }
222
223    fn required_aes(&self) -> Vec<Aesthetic> {
224        vec![Aesthetic::X, Aesthetic::Y]
225    }
226
227    fn default_stat(&self) -> Box<dyn Stat> {
228        Box::new(StatIdentity)
229    }
230
231    fn default_position(&self) -> Box<dyn Position> {
232        Box::new(PositionIdentity)
233    }
234
235    fn default_params(&self) -> GeomParams {
236        GeomParams::default()
237    }
238
239    fn name(&self) -> &str {
240        "tile"
241    }
242
243    fn setup_data(&self, data: &mut DataFrame) {
244        add_extents(data, "x", "xmin", "xmax", self.width);
245        add_extents(data, "y", "ymin", "ymax", self.height);
246    }
247
248    fn set_series_color(&mut self, color: (u8, u8, u8)) {
249        self.fill = color;
250    }
251}