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 #[cfg(feature = "regression")]
50 pub fn gam(mut self) -> Self {
51 self.method = SmoothMethod::Gam;
52 self
53 }
54
55 #[cfg(feature = "regression")]
61 pub fn glm(mut self, family: crate::stat::smooth::SmoothFamily) -> Self {
62 self.method = SmoothMethod::Glm { family };
63 self
64 }
65}
66
67impl Geom for GeomSmooth {
68 fn draw(
69 &self,
70 data: &DataFrame,
71 coord: &dyn Coord,
72 scales: &ScaleSet,
73 _theme: &Theme,
74 backend: &mut dyn DrawBackend,
75 ) -> Result<(), RenderError> {
76 let x_col = data
77 .column("x")
78 .ok_or(RenderError::MissingAesthetic("x".into()))?;
79 let y_col = data
80 .column("y")
81 .ok_or(RenderError::MissingAesthetic("y".into()))?;
82 let ymin_col = data.column("ymin");
83 let ymax_col = data.column("ymax");
84 let color_col = data.column("color");
85 let fill_col = data.column("fill");
86
87 let plot_area = backend.plot_area();
88 let x_scale = scales.get(&Aesthetic::X);
89 let y_scale = scales.get(&Aesthetic::Y);
90
91 if let Some(cc) = color_col.or(fill_col) {
93 let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
94 for (i, v) in cc.iter().enumerate() {
95 let key = v.to_group_key();
96 if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
97 entry.1.push(i);
98 } else {
99 groups.push((key, vec![i]));
100 }
101 }
102
103 for (_, indices) in &groups {
104 let first_idx = indices[0];
105
106 let line_color = color_col
108 .and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
109 .unwrap_or(self.color);
110 let ribbon_fill = fill_col
111 .and_then(|f| scales.map_color(&Aesthetic::Fill, &f[first_idx]))
112 .or_else(|| {
113 color_col.and_then(|c| scales.map_color(&Aesthetic::Color, &c[first_idx]))
114 })
115 .unwrap_or(self.fill);
116
117 if self.se {
119 if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
120 let mut upper_points: Vec<(f64, f64)> = Vec::new();
121 let mut lower_points: Vec<(f64, f64)> = Vec::new();
122
123 for &i in indices {
124 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
125 let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
126 let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
127
128 upper_points.push(coord.transform((nx, ny_max), &plot_area));
129 lower_points.push(coord.transform((nx, ny_min), &plot_area));
130 }
131
132 let mut polygon = upper_points;
133 lower_points.reverse();
134 polygon.extend(lower_points);
135
136 if polygon.len() >= 3 {
137 backend.draw_polygon(
138 &polygon,
139 &RectStyle {
140 fill: Some(ribbon_fill),
141 stroke: None,
142 stroke_width: 0.0,
143 alpha: self.alpha,
144 clip: true,
145 },
146 )?;
147 }
148 }
149 }
150
151 let points: Vec<(f64, f64)> = indices
153 .iter()
154 .map(|&i| {
155 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
156 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
157 coord.transform((nx, ny), &plot_area)
158 })
159 .collect();
160
161 if points.len() >= 2 {
162 backend.draw_line(
163 &points,
164 &LineStyle {
165 color: line_color,
166 alpha: 1.0,
167 width: self.line_width,
168 linetype: Linetype::Solid,
169 ..Default::default()
170 },
171 )?;
172 draw_hover_marks(
173 backend, &points, indices, x_col, y_col, ymin_col, ymax_col, line_color,
174 )?;
175 }
176 }
177 } else {
178 if self.se {
182 if let (Some(ymin), Some(ymax)) = (ymin_col, ymax_col) {
183 let mut upper_points: Vec<(f64, f64)> = Vec::new();
184 let mut lower_points: Vec<(f64, f64)> = Vec::new();
185
186 for i in 0..data.nrows() {
187 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
188 let ny_max = y_scale.map(|s| s.map(&ymax[i])).unwrap_or(0.0);
189 let ny_min = y_scale.map(|s| s.map(&ymin[i])).unwrap_or(0.0);
190
191 upper_points.push(coord.transform((nx, ny_max), &plot_area));
192 lower_points.push(coord.transform((nx, ny_min), &plot_area));
193 }
194
195 let mut polygon = upper_points;
197 lower_points.reverse();
198 polygon.extend(lower_points);
199
200 if polygon.len() >= 3 {
201 backend.draw_polygon(
202 &polygon,
203 &RectStyle {
204 fill: Some(self.fill),
205 stroke: None,
206 stroke_width: 0.0,
207 alpha: self.alpha,
208 clip: true,
209 },
210 )?;
211 }
212 }
213 }
214
215 let points: Vec<(f64, f64)> = (0..data.nrows())
217 .map(|i| {
218 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
219 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
220 coord.transform((nx, ny), &plot_area)
221 })
222 .collect();
223
224 if points.len() >= 2 {
225 backend.draw_line(
226 &points,
227 &LineStyle {
228 color: self.color,
229 alpha: 1.0,
230 width: self.line_width,
231 linetype: Linetype::Solid,
232 ..Default::default()
233 },
234 )?;
235 let rows: Vec<usize> = (0..data.nrows()).collect();
236 draw_hover_marks(
237 backend, &points, &rows, x_col, y_col, ymin_col, ymax_col, self.color,
238 )?;
239 }
240 }
241
242 Ok(())
243 }
244
245 fn required_aes(&self) -> Vec<Aesthetic> {
246 vec![Aesthetic::X, Aesthetic::Y]
247 }
248
249 fn default_stat(&self) -> Box<dyn Stat> {
250 Box::new(StatSmooth {
251 n_points: self.n_points,
252 se: self.se,
253 method: self.method.clone(),
254 })
255 }
256
257 fn default_position(&self) -> Box<dyn Position> {
258 Box::new(PositionIdentity)
259 }
260
261 fn default_params(&self) -> GeomParams {
262 GeomParams::default()
263 }
264
265 fn name(&self) -> &str {
266 "smooth"
267 }
268
269 fn set_series_color(&mut self, color: (u8, u8, u8)) {
270 self.color = color;
271 self.fill = color;
272 }
273}
274
275#[allow(clippy::too_many_arguments)]
280fn draw_hover_marks(
281 backend: &mut dyn DrawBackend,
282 points: &[(f64, f64)],
283 rows: &[usize],
284 x_col: &[Value],
285 y_col: &[Value],
286 ymin_col: Option<&[Value]>,
287 ymax_col: Option<&[Value]>,
288 color: (u8, u8, u8),
289) -> Result<(), RenderError> {
290 let step = (rows.len() / 40).max(1);
291 for (k, &i) in rows.iter().enumerate() {
292 if k % step != 0 {
293 continue;
294 }
295 super::set_mark(
296 backend,
297 Some(smooth_tip(y_col, ymin_col, ymax_col, i)),
298 Some(super::tip_value(&x_col[i])),
299 None,
300 super::raw_value(&y_col[i]),
301 );
302 backend.draw_shape(
303 points[k],
304 0.6,
305 &PointStyle {
306 color,
307 alpha: 0.0,
308 filled: true,
309 shape: PointShape::Circle,
310 },
311 )?;
312 }
313 super::clear_mark(backend);
314 Ok(())
315}
316
317fn smooth_tip(
319 y_col: &[Value],
320 ymin_col: Option<&[Value]>,
321 ymax_col: Option<&[Value]>,
322 i: usize,
323) -> String {
324 let yv = y_col[i]
325 .as_f64()
326 .map(|f| format!("{f:.3}"))
327 .unwrap_or_default();
328 let ci = match (ymin_col, ymax_col) {
329 (Some(lo), Some(hi)) => match (lo[i].as_f64(), hi[i].as_f64()) {
330 (Some(a), Some(b)) => format!(" [{a:.3}, {b:.3}]"),
331 _ => String::new(),
332 },
333 _ => String::new(),
334 };
335 format!("ŷ = {yv}{ci}")
336}