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::bin2d::StatBin2d;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomBin2d {
17 pub color: (u8, u8, u8),
18 pub alpha: f64,
19 pub line_width: f64,
20}
21
22impl Default for GeomBin2d {
23 fn default() -> Self {
24 GeomBin2d {
25 color: (50, 50, 50),
26 alpha: 1.0,
27 line_width: 0.2,
28 }
29 }
30}
31
32impl Geom for GeomBin2d {
33 fn draw(
34 &self,
35 data: &DataFrame,
36 coord: &dyn Coord,
37 scales: &ScaleSet,
38 _theme: &Theme,
39 backend: &mut dyn DrawBackend,
40 ) -> Result<(), RenderError> {
41 let xmin_col = data
42 .column("xmin")
43 .ok_or(RenderError::MissingAesthetic("xmin".into()))?;
44 let xmax_col = data
45 .column("xmax")
46 .ok_or(RenderError::MissingAesthetic("xmax".into()))?;
47 let ymin_col = data
48 .column("ymin")
49 .ok_or(RenderError::MissingAesthetic("ymin".into()))?;
50 let ymax_col = data
51 .column("ymax")
52 .ok_or(RenderError::MissingAesthetic("ymax".into()))?;
53 let fill_col = data.column("fill");
54
55 let plot_area = backend.plot_area();
56 let x_scale = scales.get(&Aesthetic::X);
57 let y_scale = scales.get(&Aesthetic::Y);
58
59 for i in 0..data.nrows() {
60 let nxmin = x_scale.map(|s| s.map(&xmin_col[i])).unwrap_or(0.0);
61 let nxmax = x_scale.map(|s| s.map(&xmax_col[i])).unwrap_or(0.0);
62 let nymin = y_scale.map(|s| s.map(&ymin_col[i])).unwrap_or(0.0);
63 let nymax = y_scale.map(|s| s.map(&ymax_col[i])).unwrap_or(0.0);
64
65 let (left, top) = coord.transform((nxmin, nymax), &plot_area);
66 let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
67
68 let fill_color = fill_col
69 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
70 .unwrap_or((97, 156, 255));
71
72 backend.draw_rect(
73 (left, top.min(bottom)),
74 (right, top.max(bottom)),
75 &RectStyle {
76 fill: Some(fill_color),
77 stroke: Some(self.color),
78 stroke_width: self.line_width,
79 alpha: self.alpha,
80 clip: true,
81 },
82 )?;
83 }
84
85 Ok(())
86 }
87
88 fn required_aes(&self) -> Vec<Aesthetic> {
89 vec![Aesthetic::X, Aesthetic::Y]
90 }
91
92 fn default_stat(&self) -> Box<dyn Stat> {
93 Box::new(StatBin2d::default())
94 }
95
96 fn default_position(&self) -> Box<dyn Position> {
97 Box::new(PositionIdentity)
98 }
99
100 fn default_params(&self) -> GeomParams {
101 GeomParams::default()
102 }
103
104 fn name(&self) -> &str {
105 "bin2d"
106 }
107}