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        for i in 0..data.nrows() {
59            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
60            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
61
62            let ny_base = ymin_col
63                .and_then(|c| c[i].as_f64())
64                .and_then(|v| y_scale.map(|s| s.map(&crate::data::Value::Float(v))))
65                .unwrap_or_else(|| {
66                    y_scale
67                        .map(|s| s.map(&crate::data::Value::Float(0.0)))
68                        .unwrap_or(0.0)
69                });
70
71            // Bar width in normalized coords
72            let half_width = if x_is_discrete {
73                // Band-based: each category occupies 1/n of the axis
74                let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
75                let band_width = 1.0 / n_breaks.max(1) as f64;
76                band_width * self.width / 2.0
77            } else {
78                0.02 // Thin bars for continuous
79            };
80
81            let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
82            let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
83
84            let (fr, fg, fb) = if let Some(fc) = fill_col {
85                scales
86                    .map_color(&Aesthetic::Fill, &fc[i])
87                    .unwrap_or(self.fill)
88            } else {
89                self.fill
90            };
91
92            backend.draw_rect(
93                (left_px, top_px.min(bottom_px)),
94                (right_px, top_px.max(bottom_px)),
95                &RectStyle {
96                    fill: Some((fr, fg, fb)),
97                    stroke: Some(self.color),
98                    stroke_width: 0.5,
99                    alpha: self.alpha,
100                    clip: true,
101                },
102            )?;
103        }
104
105        Ok(())
106    }
107
108    fn required_aes(&self) -> Vec<Aesthetic> {
109        vec![Aesthetic::X]
110    }
111
112    fn default_stat(&self) -> Box<dyn Stat> {
113        Box::new(StatCount)
114    }
115
116    fn default_position(&self) -> Box<dyn Position> {
117        Box::new(PositionStack)
118    }
119
120    fn default_params(&self) -> GeomParams {
121        GeomParams::default()
122    }
123
124    fn name(&self) -> &str {
125        "bar"
126    }
127
128    fn set_series_color(&mut self, color: (u8, u8, u8)) {
129        self.fill = color;
130    }
131}