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