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 = 48;
27    let mut pts = Vec::with_capacity(2 * (N + 1));
28    if coord.polar_theta_is_x() {
29        // angle = x: sweep x along the outer radius (r1), back along the inner (r0)
30        for k in 0..=N {
31            let t = t0 + (t1 - t0) * k as f64 / N as f64;
32            pts.push(coord.transform((t, r1), area));
33        }
34        for k in 0..=N {
35            let t = t1 + (t0 - t1) * k as f64 / N as f64;
36            pts.push(coord.transform((t, r0), area));
37        }
38    } else {
39        // angle = y (pie): sweep y along the outer radius (t1), back along t0
40        for k in 0..=N {
41            let r = r0 + (r1 - r0) * k as f64 / N as f64;
42            pts.push(coord.transform((t1, r), area));
43        }
44        for k in 0..=N {
45            let r = r1 + (r0 - r1) * k as f64 / N as f64;
46            pts.push(coord.transform((t0, r), area));
47        }
48    }
49    pts
50}
51
52/// Column geometry — like GeomBar but with pre-computed heights (uses StatIdentity).
53pub struct GeomCol {
54    pub fill: (u8, u8, u8),
55    pub color: (u8, u8, u8),
56    pub alpha: f64,
57    pub width: f64,
58}
59
60impl Default for GeomCol {
61    fn default() -> Self {
62        GeomCol {
63            fill: (97, 156, 255),
64            color: (50, 50, 50),
65            alpha: 1.0,
66            width: 0.9,
67        }
68    }
69}
70
71impl Geom for GeomCol {
72    fn draw(
73        &self,
74        data: &DataFrame,
75        coord: &dyn Coord,
76        scales: &ScaleSet,
77        _theme: &Theme,
78        backend: &mut dyn DrawBackend,
79    ) -> Result<(), RenderError> {
80        let x_col = data
81            .column("x")
82            .ok_or(RenderError::MissingAesthetic("x".into()))?;
83        let y_col = data
84            .column("y")
85            .ok_or(RenderError::MissingAesthetic("y".into()))?;
86        let fill_col = data.column("fill");
87
88        let plot_area = backend.plot_area();
89        let x_scale = scales.get(&Aesthetic::X);
90        let y_scale = scales.get(&Aesthetic::Y);
91        let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
92
93        let ymin_col = data.column("ymin");
94        // A `label` mapping (and the value) becomes a hover tooltip on each bar.
95        let label_col = data.column("label");
96
97        for i in 0..data.nrows() {
98            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
99            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
100            // Honor a stacked/filled base (ymin) so stacked columns draw as
101            // distinct segments rather than all from zero.
102            let ny_base = ymin_col
103                .and_then(|c| c[i].as_f64())
104                .and_then(|v| y_scale.map(|s| s.map(&crate::data::Value::Float(v))))
105                .unwrap_or_else(|| {
106                    y_scale
107                        .map(|s| s.map(&crate::data::Value::Float(0.0)))
108                        .unwrap_or(0.0)
109                });
110
111            let half_width = if x_is_discrete {
112                let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
113                let bar_frac = self.width / (n_breaks.max(1) as f64 * 1.1);
114                bar_frac / 2.0
115            } else {
116                0.02
117            };
118
119            let (fr, fg, fb) = if let Some(fc) = fill_col {
120                scales
121                    .map_color(&Aesthetic::Fill, &fc[i])
122                    .unwrap_or(self.fill)
123            } else {
124                self.fill
125            };
126            let style = RectStyle {
127                fill: Some((fr, fg, fb)),
128                stroke: Some(self.color),
129                stroke_width: 0.5,
130                alpha: self.alpha,
131                clip: !coord.is_polar(),
132            };
133
134            let label = label_col.and_then(|c| match &c[i] {
135                crate::data::Value::Str(s) if !s.is_empty() => Some(s.clone()),
136                v => v
137                    .as_f64()
138                    .map(|f| format!("{}", (f * 1000.0).round() / 1000.0)),
139            });
140            let yval = y_col[i]
141                .as_f64()
142                .map(|f| format!("{}", (f * 1000.0).round() / 1000.0));
143            backend.set_tooltip(match (label, yval) {
144                (Some(l), Some(y)) => Some(format!("{l}: {y}")),
145                (Some(l), None) => Some(l),
146                (None, Some(y)) => Some(y),
147                (None, None) => None,
148            });
149            backend.set_mark_axis(Some(super::tip_value(&x_col[i])));
150
151            if coord.is_polar() {
152                // A bar becomes a radial sector: tessellate the outer arc
153                // (radius = value) and the inner arc (radius = base) so the
154                // filled polygon follows the circle instead of a warped quad.
155                let points = polar_sector(
156                    coord,
157                    &plot_area,
158                    nx - half_width,
159                    nx + half_width,
160                    ny_base,
161                    ny,
162                );
163                backend.draw_polygon(&points, &style)?;
164            } else {
165                let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
166                let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
167                backend.draw_rect(
168                    (left_px, top_px.min(bottom_px)),
169                    (right_px, top_px.max(bottom_px)),
170                    &style,
171                )?;
172            }
173        }
174        backend.set_tooltip(None);
175        backend.set_mark_axis(None);
176
177        Ok(())
178    }
179
180    fn required_aes(&self) -> Vec<Aesthetic> {
181        vec![Aesthetic::X, Aesthetic::Y]
182    }
183
184    fn default_stat(&self) -> Box<dyn Stat> {
185        Box::new(StatIdentity)
186    }
187
188    fn default_position(&self) -> Box<dyn Position> {
189        Box::new(PositionIdentity)
190    }
191
192    fn default_params(&self) -> GeomParams {
193        GeomParams::default()
194    }
195
196    fn name(&self) -> &str {
197        "col"
198    }
199
200    fn include_zero_baseline(&self) -> bool {
201        true
202    }
203
204    fn set_series_color(&mut self, color: (u8, u8, u8)) {
205        self.fill = color;
206    }
207}