Skip to main content

ggplot_rs/geom/
col.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/// Tessellate a bar — angle span `[t0, t1]`, radius span `[r0, r1]` in
16/// normalized coords — into a radial-sector polygon of pixel points under a
17/// polar `coord`. Both arcs are sampled so the fill follows the circle.
18pub(crate) fn polar_sector(
19    coord: &dyn Coord,
20    area: &crate::render::Rect,
21    t0: f64,
22    t1: f64,
23    r0: f64,
24    r1: f64,
25) -> Vec<(f64, f64)> {
26    const N: usize = 24;
27    let mut pts = Vec::with_capacity(2 * (N + 1));
28    for k in 0..=N {
29        let t = t0 + (t1 - t0) * k as f64 / N as f64;
30        pts.push(coord.transform((t, r1), area));
31    }
32    for k in 0..=N {
33        let t = t1 + (t0 - t1) * k as f64 / N as f64;
34        pts.push(coord.transform((t, r0), area));
35    }
36    pts
37}
38
39/// Column geometry — like GeomBar but with pre-computed heights (uses StatIdentity).
40pub struct GeomCol {
41    pub fill: (u8, u8, u8),
42    pub color: (u8, u8, u8),
43    pub alpha: f64,
44    pub width: f64,
45}
46
47impl Default for GeomCol {
48    fn default() -> Self {
49        GeomCol {
50            fill: (97, 156, 255),
51            color: (50, 50, 50),
52            alpha: 1.0,
53            width: 0.9,
54        }
55    }
56}
57
58impl Geom for GeomCol {
59    fn draw(
60        &self,
61        data: &DataFrame,
62        coord: &dyn Coord,
63        scales: &ScaleSet,
64        _theme: &Theme,
65        backend: &mut dyn DrawBackend,
66    ) -> Result<(), RenderError> {
67        let x_col = data
68            .column("x")
69            .ok_or(RenderError::MissingAesthetic("x".into()))?;
70        let y_col = data
71            .column("y")
72            .ok_or(RenderError::MissingAesthetic("y".into()))?;
73        let fill_col = data.column("fill");
74
75        let plot_area = backend.plot_area();
76        let x_scale = scales.get(&Aesthetic::X);
77        let y_scale = scales.get(&Aesthetic::Y);
78        let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
79
80        for i in 0..data.nrows() {
81            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
82            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
83            let ny_base = y_scale
84                .map(|s| s.map(&crate::data::Value::Float(0.0)))
85                .unwrap_or(0.0);
86
87            let half_width = if x_is_discrete {
88                let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
89                let bar_frac = self.width / (n_breaks.max(1) as f64 * 1.1);
90                bar_frac / 2.0
91            } else {
92                0.02
93            };
94
95            let (fr, fg, fb) = if let Some(fc) = fill_col {
96                scales
97                    .map_color(&Aesthetic::Fill, &fc[i])
98                    .unwrap_or(self.fill)
99            } else {
100                self.fill
101            };
102            let style = RectStyle {
103                fill: Some((fr, fg, fb)),
104                stroke: Some(self.color),
105                stroke_width: 0.5,
106                alpha: self.alpha,
107                clip: !coord.is_polar(),
108            };
109
110            if coord.is_polar() {
111                // A bar becomes a radial sector: tessellate the outer arc
112                // (radius = value) and the inner arc (radius = base) so the
113                // filled polygon follows the circle instead of a warped quad.
114                let points = polar_sector(
115                    coord,
116                    &plot_area,
117                    nx - half_width,
118                    nx + half_width,
119                    ny_base,
120                    ny,
121                );
122                backend.draw_polygon(&points, &style)?;
123            } else {
124                let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
125                let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
126                backend.draw_rect(
127                    (left_px, top_px.min(bottom_px)),
128                    (right_px, top_px.max(bottom_px)),
129                    &style,
130                )?;
131            }
132        }
133
134        Ok(())
135    }
136
137    fn required_aes(&self) -> Vec<Aesthetic> {
138        vec![Aesthetic::X, Aesthetic::Y]
139    }
140
141    fn default_stat(&self) -> Box<dyn Stat> {
142        Box::new(StatIdentity)
143    }
144
145    fn default_position(&self) -> Box<dyn Position> {
146        Box::new(PositionIdentity)
147    }
148
149    fn default_params(&self) -> GeomParams {
150        GeomParams::default()
151    }
152
153    fn name(&self) -> &str {
154        "col"
155    }
156
157    fn set_series_color(&mut self, color: (u8, u8, u8)) {
158        self.fill = color;
159    }
160}