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        // Bar width in normalized coords — computed once, not per row (breaks()
98        // allocates every level label, which made many-category charts O(n²)).
99        let half_width = if x_is_discrete {
100            let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
101            let pad = if coord.discrete_expand() { 1.1 } else { 1.0 };
102            self.width / (n_breaks.max(1) as f64 * pad) / 2.0
103        } else {
104            super::continuous_bar_half_width(
105                x_col.iter().filter_map(|v| x_scale.map(|s| s.map(v))),
106                self.width,
107                0.02,
108            )
109        };
110
111        // A discrete-axis dodge stores per-row offsets (in category units) and
112        // the number of groups sharing the slot; bars shift and narrow by them.
113        let x_mapper = super::support::XMapper::new(data, scales);
114        let dodge_n = data.column(crate::position::DODGE_N_COL);
115
116        for i in 0..data.nrows() {
117            let nx = x_mapper.map(&x_col[i], i);
118            let half_width = match dodge_n.and_then(|c| c[i].as_f64()) {
119                Some(n) if n > 1.0 && x_is_discrete => half_width / n,
120                _ => half_width,
121            };
122            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
123            // Honor a stacked/filled base (ymin) so stacked columns draw as
124            // distinct segments rather than all from zero.
125            let ny_base = ymin_col
126                .and_then(|c| c[i].as_f64())
127                .and_then(|v| y_scale.map(|s| s.map(&crate::data::Value::Float(v))))
128                .unwrap_or_else(|| {
129                    y_scale
130                        .map(|s| s.map(&crate::data::Value::Float(0.0)))
131                        .unwrap_or(0.0)
132                });
133
134            let (fr, fg, fb) = if let Some(fc) = fill_col {
135                scales
136                    .map_color(&Aesthetic::Fill, &fc[i])
137                    .unwrap_or(self.fill)
138            } else {
139                self.fill
140            };
141            let style = RectStyle {
142                fill: Some((fr, fg, fb)),
143                stroke: Some(self.color),
144                stroke_width: 0.5,
145                alpha: self.alpha,
146                clip: !coord.is_polar(),
147            };
148
149            let label = label_col.and_then(|c| match &c[i] {
150                crate::data::Value::Str(s) if !s.is_empty() => Some(s.clone()),
151                v => v
152                    .as_f64()
153                    .map(|f| format!("{}", (f * 1000.0).round() / 1000.0)),
154            });
155            // The tooltip reports the measured value — for stacked/filled bars
156            // the segment's own value, not the cumulative stack top.
157            let raw = super::measured_value(data, i);
158            let yval = raw
159                .as_deref()
160                .and_then(|r| r.parse::<f64>().ok())
161                .map(|f| format!("{}", (f * 1000.0).round() / 1000.0));
162            let tip = match (label, yval) {
163                (Some(l), Some(y)) => Some(format!("{l}: {y}")),
164                (Some(l), None) => Some(l),
165                (None, Some(y)) => Some(y),
166                (None, None) => None,
167            };
168            super::set_mark(
169                backend,
170                tip,
171                Some(super::tip_value(&x_col[i])),
172                super::series_key(data, i),
173                raw,
174            );
175            super::set_mark_formatted(
176                backend,
177                scales,
178                Some(&x_col[i]),
179                &Aesthetic::Y,
180                super::measured_raw(data, i),
181            );
182            super::set_row_extras(backend, data, i);
183
184            if coord.is_polar() {
185                // A bar becomes a radial sector: tessellate the outer arc
186                // (radius = value) and the inner arc (radius = base) so the
187                // filled polygon follows the circle instead of a warped quad.
188                let points = polar_sector(
189                    coord,
190                    &plot_area,
191                    nx - half_width,
192                    nx + half_width,
193                    ny_base,
194                    ny,
195                );
196                backend.draw_polygon(&points, &style)?;
197            } else {
198                let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
199                let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
200                backend.draw_rect(
201                    (left_px, top_px.min(bottom_px)),
202                    (right_px, top_px.max(bottom_px)),
203                    &style,
204                )?;
205            }
206        }
207        super::clear_mark(backend);
208        super::clear_row_extras(backend);
209
210        Ok(())
211    }
212
213    fn required_aes(&self) -> Vec<Aesthetic> {
214        vec![Aesthetic::X, Aesthetic::Y]
215    }
216
217    fn default_stat(&self) -> Box<dyn Stat> {
218        Box::new(StatIdentity)
219    }
220
221    fn default_position(&self) -> Box<dyn Position> {
222        Box::new(PositionIdentity)
223    }
224
225    fn default_params(&self) -> GeomParams {
226        GeomParams::default()
227    }
228
229    fn name(&self) -> &str {
230        "col"
231    }
232
233    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
234        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
235            self.color = ink;
236        }
237    }
238
239    fn consumes_tooltips(&self) -> bool {
240        true
241    }
242
243    fn include_zero_baseline(&self) -> bool {
244        true
245    }
246
247    fn set_series_color(&mut self, color: (u8, u8, u8)) {
248        self.fill = color;
249    }
250}