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
15pub struct GeomCol {
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 GeomCol {
24 fn default() -> Self {
25 GeomCol {
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 GeomCol {
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
51 let plot_area = backend.plot_area();
52 let x_scale = scales.get(&Aesthetic::X);
53 let y_scale = scales.get(&Aesthetic::Y);
54 let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
55
56 for i in 0..data.nrows() {
57 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
58 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
59 let ny_base = y_scale
60 .map(|s| s.map(&crate::data::Value::Float(0.0)))
61 .unwrap_or(0.0);
62
63 let half_width = if x_is_discrete {
64 let n_breaks = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
65 let bar_frac = self.width / (n_breaks.max(1) as f64 * 1.1);
66 bar_frac / 2.0
67 } else {
68 0.02
69 };
70
71 let (left_px, top_px) = coord.transform((nx - half_width, ny), &plot_area);
72 let (right_px, bottom_px) = coord.transform((nx + half_width, ny_base), &plot_area);
73
74 let (fr, fg, fb) = if let Some(fc) = fill_col {
75 scales
76 .map_color(&Aesthetic::Fill, &fc[i])
77 .unwrap_or(self.fill)
78 } else {
79 self.fill
80 };
81
82 backend.draw_rect(
83 (left_px, top_px.min(bottom_px)),
84 (right_px, top_px.max(bottom_px)),
85 &RectStyle {
86 fill: Some((fr, fg, fb)),
87 stroke: Some(self.color),
88 stroke_width: 0.5,
89 alpha: self.alpha,
90 clip: true,
91 },
92 )?;
93 }
94
95 Ok(())
96 }
97
98 fn required_aes(&self) -> Vec<Aesthetic> {
99 vec![Aesthetic::X, Aesthetic::Y]
100 }
101
102 fn default_stat(&self) -> Box<dyn Stat> {
103 Box::new(StatIdentity)
104 }
105
106 fn default_position(&self) -> Box<dyn Position> {
107 Box::new(PositionIdentity)
108 }
109
110 fn default_params(&self) -> GeomParams {
111 GeomParams::default()
112 }
113
114 fn name(&self) -> &str {
115 "col"
116 }
117
118 fn set_series_color(&mut self, color: (u8, u8, u8)) {
119 self.fill = color;
120 }
121}