Skip to main content

ggplot_rs/geom/
col.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::position::stack::PositionStack;
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                corner_radius: 0.0,
148            };
149
150            let label = label_col.and_then(|c| match &c[i] {
151                crate::data::Value::Str(s) if !s.is_empty() => Some(s.clone()),
152                v => v
153                    .as_f64()
154                    .map(|f| format!("{}", (f * 1000.0).round() / 1000.0)),
155            });
156            // The tooltip reports the measured value — for stacked/filled bars
157            // the segment's own value, not the cumulative stack top.
158            let raw = super::measured_value(data, i);
159            let yval = raw
160                .as_deref()
161                .and_then(|r| r.parse::<f64>().ok())
162                .map(|f| format!("{}", (f * 1000.0).round() / 1000.0));
163            let tip = match (label, yval) {
164                (Some(l), Some(y)) => Some(format!("{l}: {y}")),
165                (Some(l), None) => Some(l),
166                (None, Some(y)) => Some(y),
167                (None, None) => None,
168            };
169            super::set_mark(
170                backend,
171                tip,
172                Some(super::tip_value(&x_col[i])),
173                super::series_key(data, i),
174                raw,
175            );
176            super::set_mark_formatted(
177                backend,
178                scales,
179                Some(&x_col[i]),
180                &Aesthetic::Y,
181                super::measured_raw(data, i),
182            );
183            super::set_row_extras(backend, data, i);
184
185            if coord.is_polar() {
186                // A bar becomes a radial sector: tessellate the outer arc
187                // (radius = value) and the inner arc (radius = base) so the
188                // filled polygon follows the circle instead of a warped quad.
189                let points = polar_sector(
190                    coord,
191                    &plot_area,
192                    nx - half_width,
193                    nx + half_width,
194                    ny_base,
195                    ny,
196                );
197                backend.draw_polygon(&points, &style)?;
198            } else {
199                let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
200                let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
201                backend.draw_rect(
202                    (left_px, top_px.min(bottom_px)),
203                    (right_px, top_px.max(bottom_px)),
204                    &style,
205                )?;
206            }
207        }
208        super::clear_mark(backend);
209        super::clear_row_extras(backend);
210
211        Ok(())
212    }
213
214    fn required_aes(&self) -> Vec<Aesthetic> {
215        vec![Aesthetic::X, Aesthetic::Y]
216    }
217
218    fn default_stat(&self) -> Box<dyn Stat> {
219        Box::new(StatIdentity)
220    }
221
222    fn default_position(&self) -> Box<dyn Position> {
223        // ggplot2 parity (sipemu/ggplot-rs#169): `geom_col()` defaults to
224        // `position_stack()`, same as `geom_bar()` (GeomBar::default_position,
225        // just above). 0.23 left this as `PositionIdentity`, a gap from
226        // `default_output_023.rs`'s `mixed_sign_data` comment, which needed
227        // an explicit `.position(PositionStack)` to exercise #154 at all.
228        Box::new(PositionStack)
229    }
230
231    fn default_params(&self) -> GeomParams {
232        GeomParams::default()
233    }
234
235    fn name(&self) -> &str {
236        "col"
237    }
238
239    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
240        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
241            self.color = ink;
242        }
243    }
244
245    fn consumes_tooltips(&self) -> bool {
246        true
247    }
248
249    fn include_zero_baseline(&self) -> bool {
250        true
251    }
252
253    fn set_series_color(&mut self, color: (u8, u8, u8)) {
254        self.fill = color;
255    }
256}