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 super::set_mark(
73 backend,
74 fill_col.map(|c| format!("n = {}", super::tip_value(&c[i]))),
75 None,
76 None,
77 fill_col.and_then(|c| super::raw_value(&c[i])),
78 );
79 backend.draw_rect(
80 (left, top.min(bottom)),
81 (right, top.max(bottom)),
82 &RectStyle {
83 fill: Some(fill_color),
84 stroke: Some(self.color),
85 stroke_width: self.line_width,
86 alpha: self.alpha,
87 clip: true,
88 },
89 )?;
90 }
91 super::clear_mark(backend);
92
93 Ok(())
94 }
95
96 fn required_aes(&self) -> Vec<Aesthetic> {
97 vec![Aesthetic::X, Aesthetic::Y]
98 }
99
100 fn default_stat(&self) -> Box<dyn Stat> {
101 Box::new(StatBin2d::default())
102 }
103
104 fn default_position(&self) -> Box<dyn Position> {
105 Box::new(PositionIdentity)
106 }
107
108 fn default_params(&self) -> GeomParams {
109 GeomParams::default()
110 }
111
112 fn name(&self) -> &str {
113 "bin2d"
114 }
115}