1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::{DataFrame, Value};
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, LineStyle, Linetype, PointShape, PointStyle, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::smooth::{SmoothMethod, StatSmooth};
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomSmooth {
17 pub color: (u8, u8, u8),
18 pub fill: (u8, u8, u8),
19 pub line_width: f64,
20 pub alpha: f64,
21 pub se: bool,
22 pub n_points: usize,
23 pub method: SmoothMethod,
24}
25
26impl Default for GeomSmooth {
27 fn default() -> Self {
28 GeomSmooth {
29 color: (51, 102, 204),
30 fill: (51, 102, 204),
31 line_width: 1.5,
32 alpha: 0.2,
33 se: true,
34 n_points: 80,
35 method: SmoothMethod::Lm,
36 }
37 }
38}
39
40impl GeomSmooth {
41 pub fn loess(mut self, span: f64) -> Self {
43 self.method = SmoothMethod::Loess { span };
44 self
45 }
46
47 pub fn gam(mut self) -> Self {
53 self.method = SmoothMethod::Gam;
54 self
55 }
56
57 #[cfg(feature = "regression")]
63 pub fn glm(mut self, family: crate::stat::smooth::SmoothFamily) -> Self {
64 self.method = SmoothMethod::Glm { family };
65 self
66 }
67}
68
69impl Geom for GeomSmooth {
70 fn draw(
71 &self,
72 data: &DataFrame,
73 coord: &dyn Coord,
74 scales: &ScaleSet,
75 _theme: &Theme,
76 backend: &mut dyn DrawBackend,
77 ) -> Result<(), RenderError> {
78 let x_col = data
79 .column("x")
80 .ok_or(RenderError::MissingAesthetic("x".into()))?;
81 let y_col = data
82 .column("y")
83 .ok_or(RenderError::MissingAesthetic("y".into()))?;
84 let ymin_col = data.column("ymin");
85 let ymax_col = data.column("ymax");
86 let color_col = data.column("color");
87 let fill_col = data.column("fill");
88
89 let plot_area = backend.plot_area();
90 let x_scale = scales.get(&Aesthetic::X);
91 let y_scale = scales.get(&Aesthetic::Y);
92
93 if let Some(cc) = color_col.or(fill_col).or_else(|| data.column("group")) {
96 let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
97 for (i, v) in cc.iter().enumerate() {
98 let key = v.to_group_key();
99 if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
100 entry.1.push(i);
101 } else {
102 groups.push((key, vec![i]));
103 }
104 }
105
106 for (_, indices) in &groups {
107 let first_idx = indices[0];
108
109 let line_color = color_col
111 .and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
112 .unwrap_or(self.color);
113 let ribbon_fill = fill_col
114 .and_then(|f| scales.map_color(&Aesthetic::Fill, &f[first_idx]))
115 .or_else(|| {
116 color_col.and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
117 })
118 .unwrap_or(self.fill);
119
120 if self.se {
122 if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
123 let mut upper_points: Vec<(f64, f64)> = Vec::new();
124 let mut lower_points: Vec<(f64, f64)> = Vec::new();
125
126 for &i in indices {
127 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
128 let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
129 let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
130
131 upper_points.push(coord.transform((nx, ny_max), &plot_area));
132 lower_points.push(coord.transform((nx, ny_min), &plot_area));
133 }
134
135 let mut polygon = upper_points;
136 lower_points.reverse();
137 polygon.extend(lower_points);
138
139 if polygon.len() >= 3 {
140 backend.draw_polygon(
141 &polygon,
142 &RectStyle {
143 fill: Some(ribbon_fill),
144 stroke: None,
145 stroke_width: 0.0,
146 alpha: self.alpha,
147 clip: true,
148 corner_radius: 0.0,
149 },
150 )?;
151 }
152 }
153 }
154
155 let points: Vec<(f64, f64)> = indices
157 .iter()
158 .map(|&i| {
159 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
160 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
161 coord.transform((nx, ny), &plot_area)
162 })
163 .collect();
164
165 if points.len() >= 2 {
166 backend.draw_line(
167 &points,
168 &LineStyle {
169 color: line_color,
170 alpha: 1.0,
171 width: self.line_width,
172 linetype: Linetype::Solid,
173 ..Default::default()
174 },
175 )?;
176 draw_hover_marks(
177 backend, scales, &points, indices, x_col, y_col, ymin_col, ymax_col,
178 line_color,
179 )?;
180 }
181 }
182 } else {
183 if self.se {
187 if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
188 let mut upper_points: Vec<(f64, f64)> = Vec::new();
189 let mut lower_points: Vec<(f64, f64)> = Vec::new();
190
191 for i in 0..data.nrows() {
192 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
193 let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
194 let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
195
196 upper_points.push(coord.transform((nx, ny_max), &plot_area));
197 lower_points.push(coord.transform((nx, ny_min), &plot_area));
198 }
199
200 let mut polygon = upper_points;
202 lower_points.reverse();
203 polygon.extend(lower_points);
204
205 if polygon.len() >= 3 {
206 backend.draw_polygon(
207 &polygon,
208 &RectStyle {
209 fill: Some(self.fill),
210 stroke: None,
211 stroke_width: 0.0,
212 alpha: self.alpha,
213 clip: true,
214 corner_radius: 0.0,
215 },
216 )?;
217 }
218 }
219 }
220
221 let points: Vec<(f64, f64)> = (0..data.nrows())
223 .map(|i| {
224 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
225 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
226 coord.transform((nx, ny), &plot_area)
227 })
228 .collect();
229
230 if points.len() >= 2 {
231 backend.draw_line(
232 &points,
233 &LineStyle {
234 color: self.color,
235 alpha: 1.0,
236 width: self.line_width,
237 linetype: Linetype::Solid,
238 ..Default::default()
239 },
240 )?;
241 let rows: Vec<usize> = (0..data.nrows()).collect();
242 draw_hover_marks(
243 backend, scales, &points, &rows, x_col, y_col, ymin_col, ymax_col, self.color,
244 )?;
245 }
246 }
247
248 Ok(())
249 }
250
251 fn required_aes(&self) -> Vec<Aesthetic> {
252 vec![Aesthetic::X, Aesthetic::Y]
253 }
254
255 fn default_stat(&self) -> Box<dyn Stat> {
256 Box::new(StatSmooth {
257 n_points: self.n_points,
258 se: self.se,
259 method: self.method.clone(),
260 })
261 }
262
263 fn default_position(&self) -> Box<dyn Position> {
264 Box::new(PositionIdentity)
265 }
266
267 fn default_params(&self) -> GeomParams {
268 GeomParams::default()
269 }
270
271 fn name(&self) -> &str {
272 "smooth"
273 }
274
275 fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
276 const DEFAULT: (u8, u8, u8) = (51, 102, 204);
277 if let (true, Some(accent)) = (self.color == DEFAULT, el.accent) {
278 self.color = accent;
279 }
280 if let (true, Some(accent)) = (self.fill == DEFAULT, el.accent) {
281 self.fill = accent;
282 }
283 }
284
285 fn set_series_color(&mut self, color: (u8, u8, u8)) {
286 self.color = color;
287 self.fill = color;
288 }
289}
290
291#[allow(clippy::too_many_arguments)]
296fn draw_hover_marks(
297 backend: &mut dyn DrawBackend,
298 scales: &ScaleSet,
299 points: &[(f64, f64)],
300 rows: &[usize],
301 x_col: &[Value],
302 y_col: &[Value],
303 ymin_col: Option<&[Value]>,
304 ymax_col: Option<&[Value]>,
305 color: (u8, u8, u8),
306) -> Result<(), RenderError> {
307 let step = (rows.len() / 40).max(1);
308 for (k, &i) in rows.iter().enumerate() {
309 if k % step != 0 {
310 continue;
311 }
312 super::set_mark(
313 backend,
314 Some(smooth_tip(y_col, ymin_col, ymax_col, i)),
315 Some(super::tip_value(&x_col[i])),
316 None,
317 super::raw_value(&y_col[i]),
318 );
319 super::set_mark_formatted(
320 backend,
321 scales,
322 Some(&x_col[i]),
323 &Aesthetic::Y,
324 Some(&y_col[i]),
325 );
326 backend.draw_shape(
327 points[k],
328 0.6,
329 &PointStyle {
330 color,
331 alpha: 0.0,
332 filled: true,
333 shape: PointShape::Circle,
334 },
335 )?;
336 }
337 super::clear_mark(backend);
338 Ok(())
339}
340
341fn smooth_tip(
343 y_col: &[Value],
344 ymin_col: Option<&[Value]>,
345 ymax_col: Option<&[Value]>,
346 i: usize,
347) -> String {
348 let yv = y_col[i]
349 .as_f64()
350 .map(|f| format!("{f:.3}"))
351 .unwrap_or_default();
352 let ci = match (ymin_col, ymax_col) {
353 (Some(lo), Some(hi)) => match (lo[i].as_f64(), hi[i].as_f64()) {
354 (Some(a), Some(b)) => format!(" [{a:.3}, {b:.3}]"),
355 _ => String::new(),
356 },
357 _ => String::new(),
358 };
359 format!("ŷ = {yv}{ci}")
360}