Skip to main content

ggplot_rs/geom/
hex.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::binhex::StatBinHex;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Hexagonal binning geometry — draws regular hexagon polygons per cell.
16pub struct GeomHex {
17    pub color: (u8, u8, u8),
18    pub alpha: f64,
19    pub line_width: f64,
20}
21
22impl Default for GeomHex {
23    fn default() -> Self {
24        GeomHex {
25            color: (50, 50, 50),
26            alpha: 1.0,
27            line_width: 0.2,
28        }
29    }
30}
31
32impl GeomHex {
33    /// Generate 6 vertices of a regular hexagon centered at (cx, cy) with given radius.
34    fn hex_vertices(cx: f64, cy: f64, rx: f64, ry: f64) -> Vec<(f64, f64)> {
35        (0..6)
36            .map(|k| {
37                let angle = std::f64::consts::PI / 3.0 * k as f64 + std::f64::consts::PI / 6.0;
38                (cx + rx * angle.cos(), cy + ry * angle.sin())
39            })
40            .collect()
41    }
42}
43
44impl Geom for GeomHex {
45    fn draw(
46        &self,
47        data: &DataFrame,
48        coord: &dyn Coord,
49        scales: &ScaleSet,
50        _theme: &Theme,
51        backend: &mut dyn DrawBackend,
52    ) -> Result<(), RenderError> {
53        let x_col = data
54            .column("x")
55            .ok_or(RenderError::MissingAesthetic("x".into()))?;
56        let y_col = data
57            .column("y")
58            .ok_or(RenderError::MissingAesthetic("y".into()))?;
59        let fill_col = data.column("fill");
60
61        let plot_area = backend.plot_area();
62        let x_scale = scales.get(&Aesthetic::X);
63        let y_scale = scales.get(&Aesthetic::Y);
64
65        // Determine hex size in pixel space from data density
66        // Use a fixed fraction of the plot area
67        let plot_w = plot_area.width;
68        let plot_h = plot_area.height;
69        let n_hex = (data.nrows() as f64).sqrt().max(1.0);
70        let hex_rx = plot_w / (n_hex * 2.5);
71        let hex_ry = plot_h / (n_hex * 2.5);
72
73        for i in 0..data.nrows() {
74            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
75            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
76            let (px, py) = coord.transform((nx, ny), &plot_area);
77
78            let fill_color = fill_col
79                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
80                .unwrap_or((97, 156, 255));
81
82            let vertices = Self::hex_vertices(px, py, hex_rx, hex_ry);
83
84            backend.draw_polygon(
85                &vertices,
86                &RectStyle {
87                    fill: Some(fill_color),
88                    stroke: Some(self.color),
89                    stroke_width: self.line_width,
90                    alpha: self.alpha,
91                    clip: true,
92                },
93            )?;
94        }
95
96        Ok(())
97    }
98
99    fn required_aes(&self) -> Vec<Aesthetic> {
100        vec![Aesthetic::X, Aesthetic::Y]
101    }
102
103    fn default_stat(&self) -> Box<dyn Stat> {
104        Box::new(StatBinHex::default())
105    }
106
107    fn default_position(&self) -> Box<dyn Position> {
108        Box::new(PositionIdentity)
109    }
110
111    fn default_params(&self) -> GeomParams {
112        GeomParams::default()
113    }
114
115    fn name(&self) -> &str {
116        "hex"
117    }
118}