1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::{DataFrame, Value};
4use crate::position::stack::PositionStack;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, LineStyle, Linetype, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::align::StatAlign;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomArea {
17 pub fill: (u8, u8, u8),
18 pub color: (u8, u8, u8),
19 pub alpha: f64,
20 pub line_width: f64,
21 pub interpolate: super::support::Interpolate,
24}
25
26impl Default for GeomArea {
27 fn default() -> Self {
28 GeomArea {
29 fill: (97, 156, 255),
30 color: (50, 50, 50),
31 alpha: 0.4,
32 line_width: 1.0,
33 interpolate: super::support::Interpolate::Linear,
34 }
35 }
36}
37
38impl Geom for GeomArea {
39 fn key_fill(&self) -> Option<((u8, u8, u8), f64)> {
40 Some((self.fill, self.alpha))
41 }
42
43 fn draw(
44 &self,
45 data: &DataFrame,
46 coord: &dyn Coord,
47 scales: &ScaleSet,
48 _theme: &Theme,
49 backend: &mut dyn DrawBackend,
50 ) -> Result<(), RenderError> {
51 let x_col = data
52 .column("x")
53 .ok_or(RenderError::MissingAesthetic("x".into()))?;
54 let y_col = data
55 .column("y")
56 .ok_or(RenderError::MissingAesthetic("y".into()))?;
57
58 let group_col = data
61 .column("fill")
62 .or_else(|| data.column("color"))
63 .or_else(|| data.column("group"));
64 let ymin_col = data.column("ymin");
67
68 let plot_area = backend.plot_area();
69 let x_scale = scales.get(&Aesthetic::X);
70 let y_scale = scales.get(&Aesthetic::Y);
71 let base_ny = y_scale.map(|s| s.map(&Value::Float(0.0))).unwrap_or(0.0);
72
73 let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
76 match group_col {
77 Some(gc) => {
78 for (i, v) in gc.iter().enumerate() {
79 let key = v.to_group_key();
80 match groups.iter_mut().find(|(k, _)| k == &key) {
81 Some((_, idx)) => idx.push(i),
82 None => groups.push((key, vec![i])),
83 }
84 }
85 }
86 None => groups.push((String::new(), (0..data.nrows()).collect())),
87 }
88
89 for (_, indices) in &groups {
90 let mut idx = indices.clone();
92 idx.sort_by(|&a, &b| {
93 let xa = x_scale.map(|s| s.map(&x_col[a])).unwrap_or(0.0);
94 let xb = x_scale.map(|s| s.map(&x_col[b])).unwrap_or(0.0);
95 xa.total_cmp(&xb)
96 });
97
98 let fill = group_col
99 .and_then(|gc| scales.map_color(&Aesthetic::Fill, &gc[idx[0]]))
100 .or_else(|| {
101 group_col.and_then(|gc| scales.map_color(&Aesthetic::Color, &gc[idx[0]]))
102 })
103 .unwrap_or(self.fill);
104
105 let mut upper_raw: Vec<(f64, f64)> = Vec::with_capacity(idx.len());
106 let mut lower_raw: Vec<(f64, f64)> = Vec::with_capacity(idx.len());
107 for &i in &idx {
108 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
109 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
110 let nb = ymin_col
111 .and_then(|c| c[i].as_f64())
112 .and_then(|v| y_scale.map(|s| s.map(&Value::Float(v))))
113 .unwrap_or(base_ny);
114 upper_raw.push((nx, ny));
115 lower_raw.push((nx, nb));
116 }
117 let to_px = |pts: Vec<(f64, f64)>| -> Vec<(f64, f64)> {
118 super::support::interpolate(&pts, self.interpolate)
119 .0
120 .into_iter()
121 .map(|p| coord.transform(p, &plot_area))
122 .collect()
123 };
124 let (upper, mut lower) = (to_px(upper_raw), to_px(lower_raw));
125
126 let mut polygon = upper.clone();
127 lower.reverse();
128 polygon.extend(lower);
129 if polygon.len() >= 3 {
130 backend.draw_polygon(
131 &polygon,
132 &RectStyle {
133 fill: Some(fill),
134 stroke: None,
135 stroke_width: 0.0,
136 alpha: self.alpha,
137 clip: true,
138 corner_radius: 0.0,
139 },
140 )?;
141 }
142 if upper.len() >= 2 {
143 let line_color = if groups.len() > 1 { fill } else { self.color };
146 backend.draw_line(
147 &upper,
148 &LineStyle {
149 color: line_color,
150 alpha: 1.0,
151 width: self.line_width,
152 linetype: Linetype::Solid,
153 ..Default::default()
154 },
155 )?;
156 }
157 }
158
159 Ok(())
160 }
161
162 fn required_aes(&self) -> Vec<Aesthetic> {
163 vec![Aesthetic::X, Aesthetic::Y]
164 }
165
166 fn default_stat(&self) -> Box<dyn Stat> {
167 Box::new(StatAlign)
171 }
172 fn default_position(&self) -> Box<dyn Position> {
173 Box::new(PositionStack)
180 }
181 fn default_params(&self) -> GeomParams {
182 GeomParams::default()
183 }
184 fn name(&self) -> &str {
185 "area"
186 }
187
188 fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
189 if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
190 self.color = ink;
191 }
192 }
193
194 fn include_zero_baseline(&self) -> bool {
195 true
196 }
197
198 fn set_series_color(&mut self, color: (u8, u8, u8)) {
199 self.fill = color;
200 }
201}