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) with given width/height.
16pub struct GeomTile {
17    pub fill: (u8, u8, u8),
18    pub color: (u8, u8, u8),
19    pub alpha: f64,
20    pub width: f64,
21    pub height: f64,
22    pub line_width: f64,
23}
24
25impl Default for GeomTile {
26    fn default() -> Self {
27        GeomTile {
28            fill: (97, 156, 255),
29            color: (50, 50, 50),
30            alpha: 1.0,
31            width: 1.0,
32            height: 1.0,
33            line_width: 0.5,
34        }
35    }
36}
37
38impl Geom for GeomTile {
39    fn draw(
40        &self,
41        data: &DataFrame,
42        coord: &dyn Coord,
43        scales: &ScaleSet,
44        _theme: &Theme,
45        backend: &mut dyn DrawBackend,
46    ) -> Result<(), RenderError> {
47        let x_col = data
48            .column("x")
49            .ok_or(RenderError::MissingAesthetic("x".into()))?;
50        let y_col = data
51            .column("y")
52            .ok_or(RenderError::MissingAesthetic("y".into()))?;
53        let fill_col = data.column("fill");
54        // A `label` (or the fill value) becomes each tile's hover tooltip.
55        let label_col = data.column("label").or(fill_col);
56
57        let plot_area = backend.plot_area();
58        let x_scale = scales.get(&Aesthetic::X);
59        let y_scale = scales.get(&Aesthetic::Y);
60
61        let half_w = self.width / 2.0;
62        let half_h = self.height / 2.0;
63        // Discrete axes (categorical heatmap): centre the tile on the category
64        // and size it to the break spacing; continuous axes use data ± half.
65        let x_disc = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
66        let y_disc = y_scale.map(|s| s.is_discrete()).unwrap_or(false);
67        let nbx = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
68        let nby = y_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
69
70        for i in 0..data.nrows() {
71            let (nxmin, nxmax) = if x_disc {
72                let nc = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
73                let hw = self.width / (nbx * 2.0);
74                (nc - hw, nc + hw)
75            } else {
76                let cx = x_col[i].as_f64().unwrap_or(0.0);
77                (
78                    x_scale
79                        .map(|s| s.map(&crate::data::Value::Float(cx - half_w)))
80                        .unwrap_or(0.0),
81                    x_scale
82                        .map(|s| s.map(&crate::data::Value::Float(cx + half_w)))
83                        .unwrap_or(0.0),
84                )
85            };
86            let (nymin, nymax) = if y_disc {
87                let nc = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
88                let hh = self.height / (nby * 2.0);
89                (nc - hh, nc + hh)
90            } else {
91                let cy = y_col[i].as_f64().unwrap_or(0.0);
92                (
93                    y_scale
94                        .map(|s| s.map(&crate::data::Value::Float(cy - half_h)))
95                        .unwrap_or(0.0),
96                    y_scale
97                        .map(|s| s.map(&crate::data::Value::Float(cy + half_h)))
98                        .unwrap_or(0.0),
99                )
100            };
101
102            let (left, top) = coord.transform((nxmin, nymax), &plot_area);
103            let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
104
105            let fill_color = fill_col
106                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
107                .unwrap_or(self.fill);
108
109            // Hover tooltip: "x, y: value".
110            let xs = super::tip_value(&x_col[i]);
111            let ys = super::tip_value(&y_col[i]);
112            let tip = match label_col
113                .map(|c| super::tip_value(&c[i]))
114                .filter(|s| !s.is_empty())
115            {
116                Some(v) => format!("{xs}, {ys}: {v}"),
117                None => format!("{xs}, {ys}"),
118            };
119            backend.set_tooltip(Some(tip));
120
121            backend.draw_rect(
122                (left, top.min(bottom)),
123                (right, top.max(bottom)),
124                &RectStyle {
125                    fill: Some(fill_color),
126                    stroke: Some(self.color),
127                    stroke_width: self.line_width,
128                    alpha: self.alpha,
129                    clip: true,
130                },
131            )?;
132        }
133        backend.set_tooltip(None);
134
135        Ok(())
136    }
137
138    fn required_aes(&self) -> Vec<Aesthetic> {
139        vec![Aesthetic::X, Aesthetic::Y]
140    }
141
142    fn default_stat(&self) -> Box<dyn Stat> {
143        Box::new(StatIdentity)
144    }
145
146    fn default_position(&self) -> Box<dyn Position> {
147        Box::new(PositionIdentity)
148    }
149
150    fn default_params(&self) -> GeomParams {
151        GeomParams::default()
152    }
153
154    fn name(&self) -> &str {
155        "tile"
156    }
157
158    fn set_series_color(&mut self, color: (u8, u8, u8)) {
159        self.fill = color;
160    }
161}