Skip to main content

ggplot_rs/geom/
bar.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::count::StatCount;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Bar geometry for bar charts.
16pub struct GeomBar {
17    pub fill: (u8, u8, u8),
18    pub color: (u8, u8, u8),
19    pub alpha: f64,
20    pub width: f64,
21}
22
23impl Default for GeomBar {
24    fn default() -> Self {
25        GeomBar {
26            fill: (97, 156, 255),
27            color: (50, 50, 50),
28            alpha: 1.0,
29            width: 0.9,
30        }
31    }
32}
33
34impl Geom for GeomBar {
35    fn draw(
36        &self,
37        data: &DataFrame,
38        coord: &dyn Coord,
39        scales: &ScaleSet,
40        _theme: &Theme,
41        backend: &mut dyn DrawBackend,
42    ) -> Result<(), RenderError> {
43        let x_col = data
44            .column("x")
45            .ok_or(RenderError::MissingAesthetic("x".into()))?;
46        let y_col = data
47            .column("y")
48            .ok_or(RenderError::MissingAesthetic("y".into()))?;
49        let fill_col = data.column("fill");
50        let ymin_col = data.column("ymin");
51
52        let plot_area = backend.plot_area();
53        let x_scale = scales.get(&Aesthetic::X);
54        let y_scale = scales.get(&Aesthetic::Y);
55
56        let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
57
58        // Bar width in normalized coords — computed once, not per row (breaks()
59        // allocates every level label, which made many-category charts O(n²)).
60        let half_width = if x_is_discrete {
61            // Band-based: each category occupies 1/n of the axis
62            let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
63            self.width / n_breaks.max(1) as f64 / 2.0
64        } else {
65            super::continuous_bar_half_width(
66                x_col.iter().filter_map(|v| x_scale.map(|s| s.map(v))),
67                self.width,
68                0.02,
69            )
70        };
71
72        for i in 0..data.nrows() {
73            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
74            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
75
76            let ny_base = ymin_col
77                .and_then(|c| c[i].as_f64())
78                .and_then(|v| y_scale.map(|s| s.map(&crate::data::Value::Float(v))))
79                .unwrap_or_else(|| {
80                    y_scale
81                        .map(|s| s.map(&crate::data::Value::Float(0.0)))
82                        .unwrap_or(0.0)
83                });
84
85            let (fr, fg, fb) = if let Some(fc) = fill_col {
86                scales
87                    .map_color(&Aesthetic::Fill, &fc[i])
88                    .unwrap_or(self.fill)
89            } else {
90                self.fill
91            };
92            let style = RectStyle {
93                fill: Some((fr, fg, fb)),
94                stroke: Some(self.color),
95                stroke_width: 0.5,
96                alpha: self.alpha,
97                clip: !coord.is_polar(),
98            };
99
100            // Hover: "<series>: <count>" with data-x / data-series / data-value.
101            let raw = super::measured_value(data, i);
102            let series = super::series_key(data, i);
103            let tip = raw.as_ref().map(|v| match &series {
104                Some(s) => format!("{s}: {v}"),
105                None => v.clone(),
106            });
107            super::set_mark(backend, tip, Some(super::tip_value(&x_col[i])), series, raw);
108
109            if coord.is_polar() {
110                let points = super::col::polar_sector(
111                    coord,
112                    &plot_area,
113                    nx - half_width,
114                    nx + half_width,
115                    ny_base,
116                    ny,
117                );
118                backend.draw_polygon(&points, &style)?;
119            } else {
120                let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
121                let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
122                backend.draw_rect(
123                    (left_px, top_px.min(bottom_px)),
124                    (right_px, top_px.max(bottom_px)),
125                    &style,
126                )?;
127            }
128        }
129        super::clear_mark(backend);
130
131        Ok(())
132    }
133
134    fn required_aes(&self) -> Vec<Aesthetic> {
135        vec![Aesthetic::X]
136    }
137
138    fn default_stat(&self) -> Box<dyn Stat> {
139        Box::new(StatCount)
140    }
141
142    fn default_position(&self) -> Box<dyn Position> {
143        Box::new(PositionStack)
144    }
145
146    fn default_params(&self) -> GeomParams {
147        GeomParams::default()
148    }
149
150    fn name(&self) -> &str {
151        "bar"
152    }
153
154    fn include_zero_baseline(&self) -> bool {
155        true
156    }
157
158    fn set_series_color(&mut self, color: (u8, u8, u8)) {
159        self.fill = color;
160    }
161}