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