1use std::collections::HashMap;
2
3use crate::aes::Aesthetic;
4use crate::coord::Coord;
5use crate::data::DataFrame;
6use crate::position::Position;
7use crate::render::backend::{DrawBackend, LineStyle, Linetype, RectStyle};
8use crate::render::RenderError;
9use crate::scale::ScaleSet;
10use crate::stat::ydensity::StatYDensity;
11use crate::stat::Stat;
12use crate::theme::Theme;
13
14use super::{Geom, GeomParams};
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub enum ViolinScale {
19 #[default]
21 Area,
22 Count,
24 Width,
26}
27
28#[derive(Clone, Debug)]
30pub struct GeomViolin {
31 pub fill: (u8, u8, u8),
32 pub color: (u8, u8, u8),
33 pub alpha: f64,
34 pub line_width: f64,
35 pub scale: ViolinScale,
37 pub trim: bool,
39 pub bw: Option<f64>,
41 pub adjust: f64,
43 pub quantiles: Vec<f64>,
45 pub quantile_linetype: Linetype,
47 pub quantile_color: Option<(u8, u8, u8)>,
49}
50
51impl Default for GeomViolin {
52 fn default() -> Self {
53 GeomViolin {
54 fill: (97, 156, 255),
55 color: (50, 50, 50),
56 alpha: 0.7,
57 line_width: 0.5,
58 scale: ViolinScale::Area,
59 trim: true,
60 bw: None,
61 adjust: 1.0,
62 quantiles: Vec::new(),
63 quantile_linetype: Linetype::Solid,
64 quantile_color: None,
65 }
66 }
67}
68
69impl GeomViolin {
70 pub fn with_scale(mut self, scale: ViolinScale) -> Self {
72 self.scale = scale;
73 self
74 }
75
76 pub fn untrimmed(mut self) -> Self {
78 self.trim = false;
79 self
80 }
81
82 pub fn with_bw(mut self, bw: f64) -> Self {
84 self.bw = Some(bw);
85 self
86 }
87
88 pub fn with_adjust(mut self, adjust: f64) -> Self {
90 self.adjust = adjust;
91 self
92 }
93
94 pub fn with_quantiles(mut self, q: impl IntoIterator<Item = f64>) -> Self {
96 self.quantiles = q.into_iter().collect();
97 self
98 }
99}
100
101impl Geom for GeomViolin {
102 fn draw(
103 &self,
104 data: &DataFrame,
105 coord: &dyn Coord,
106 scales: &ScaleSet,
107 _theme: &Theme,
108 backend: &mut dyn DrawBackend,
109 ) -> Result<(), RenderError> {
110 let x_col = data
111 .column("x")
112 .ok_or(RenderError::MissingAesthetic("x".into()))?;
113 let y_col = data
114 .column("y")
115 .ok_or(RenderError::MissingAesthetic("y".into()))?;
116 let width_col = data
117 .column("violinwidth")
118 .ok_or(RenderError::MissingAesthetic("violinwidth".into()))?;
119 let fill_col = data.column("fill");
120
121 let plot_area = backend.plot_area();
122 let x_scale = scales.get(&Aesthetic::X);
123 let y_scale = scales.get(&Aesthetic::Y);
124
125 let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
129 let max_half_width = if x_is_discrete {
130 let n = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
131 0.75 / (n.max(1) as f64 * 2.5)
132 } else {
133 0.03
134 };
135
136 let x_mapper = super::support::XMapper::new(data, scales);
139 let density_col = data.column("density");
142 let n_col = data.column("n");
143 let max_of = |c: Option<&[crate::data::Value]>| {
144 c.map(|c| c.iter().filter_map(|v| v.as_f64()).fold(0.0_f64, f64::max))
145 .unwrap_or(0.0)
146 };
147 let (max_density, max_n) = (max_of(density_col), max_of(n_col));
148 let rel_width = |i: usize| -> f64 {
149 let own = width_col[i].as_f64().unwrap_or(0.0);
150 match self.scale {
151 ViolinScale::Width => own,
152 ViolinScale::Area => match density_col.and_then(|c| c[i].as_f64()) {
153 Some(d) if max_density > 0.0 => d / max_density,
154 _ => own,
155 },
156 ViolinScale::Count => match n_col.and_then(|c| c[i].as_f64()) {
157 Some(n) if max_n > 0.0 => own * n / max_n,
158 _ => own,
159 },
160 }
161 };
162 let series: Vec<Option<String>> = (0..data.nrows())
163 .map(|i| super::series_key(data, i))
164 .collect();
165
166 let mut order: Vec<String> = Vec::new();
171 let mut groups: HashMap<String, Vec<usize>> = HashMap::new();
172 for (i, xv) in x_col.iter().enumerate() {
173 let key = format!("{xv:?}\u{1f}{:?}", series[i]);
174 if !groups.contains_key(&key) {
175 order.push(key.clone());
176 groups.insert(key.clone(), Vec::new());
177 }
178 groups.get_mut(&key).unwrap().push(i);
179 }
180
181 for key in &order {
182 let idxs = &groups[key];
183 let first = idxs[0];
184 let nx = if x_scale.is_some() {
185 x_mapper.map(&x_col[first], first)
186 } else {
187 0.5
188 };
189 let max_half_width = max_half_width / x_mapper.slot_n(first);
190 let fill_color = fill_col
191 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first]))
192 .unwrap_or(self.fill);
193 let group = Some(super::tip_value(&x_col[first])).filter(|s| !s.is_empty());
194 super::set_mark(
195 backend,
196 group.clone(),
197 group,
198 super::series_key(data, first),
199 None,
200 );
201 super::set_mark_formatted(backend, scales, Some(&x_col[first]), &Aesthetic::Y, None);
202
203 let mut right_side: Vec<(f64, f64)> = Vec::with_capacity(idxs.len());
205 let mut left_side: Vec<(f64, f64)> = Vec::with_capacity(idxs.len());
206 for &i in idxs {
207 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
208 let half = rel_width(i) * max_half_width;
209 right_side.push(coord.transform((nx + half, ny), &plot_area));
210 left_side.push(coord.transform((nx - half, ny), &plot_area));
211 }
212
213 let mut polygon = right_side;
214 left_side.reverse();
215 polygon.extend(left_side);
216
217 if polygon.len() >= 3 {
218 backend.draw_polygon(
219 &polygon,
220 &RectStyle {
221 fill: Some(fill_color),
222 stroke: Some(self.color),
223 stroke_width: self.line_width,
224 alpha: self.alpha,
225 clip: true,
226 corner_radius: 0.0,
227 },
228 )?;
229 }
230
231 let quantiles = data
234 .column("quantiles")
235 .and_then(|c| c[first].as_str().map(str::to_string));
236 if let Some(q) = quantiles {
237 let mut profile: Vec<(f64, f64)> = idxs
238 .iter()
239 .filter_map(|&i| y_col[i].as_f64().map(|y| (y, rel_width(i))))
240 .collect();
241 profile.sort_by(|a, b| a.0.total_cmp(&b.0));
242 for qy in q.split(',').filter_map(|v| v.parse::<f64>().ok()) {
243 let Some(w) = interpolate(&profile, qy) else {
244 continue;
245 };
246 let half = w * max_half_width;
247 let ny = y_scale.map(|s| s.map(&crate::data::Value::Float(qy)));
248 let Some(ny) = ny else { continue };
249 backend.draw_line(
250 &[
251 coord.transform((nx - half, ny), &plot_area),
252 coord.transform((nx + half, ny), &plot_area),
253 ],
254 &LineStyle {
255 color: self.quantile_color.unwrap_or(self.color),
256 width: self.line_width.max(0.5),
257 alpha: 1.0,
258 linetype: self.quantile_linetype.clone(),
259 ..Default::default()
260 },
261 )?;
262 }
263 }
264 }
265 super::clear_mark(backend);
266
267 Ok(())
268 }
269
270 fn required_aes(&self) -> Vec<Aesthetic> {
271 vec![Aesthetic::X, Aesthetic::Y]
272 }
273
274 fn default_stat(&self) -> Box<dyn Stat> {
275 Box::new(StatYDensity {
276 trim: self.trim,
277 bw: self.bw,
278 adjust: self.adjust,
279 quantiles: self.quantiles.clone(),
280 ..Default::default()
281 })
282 }
283
284 fn default_position(&self) -> Box<dyn Position> {
286 Box::new(crate::position::dodge::PositionDodge)
287 }
288
289 fn default_params(&self) -> GeomParams {
290 GeomParams::default()
291 }
292
293 fn name(&self) -> &str {
294 "violin"
295 }
296
297 fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
298 if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
299 self.color = ink;
300 }
301 }
302
303 fn set_series_color(&mut self, color: (u8, u8, u8)) {
304 self.fill = color;
305 }
306}
307
308fn interpolate(profile: &[(f64, f64)], y: f64) -> Option<f64> {
310 let (first, last) = (profile.first()?, profile.last()?);
311 if y < first.0 || y > last.0 {
312 return None;
313 }
314 let k = profile.partition_point(|p| p.0 < y);
315 if k == 0 {
316 return Some(first.1);
317 }
318 let (a, b) = (profile[k - 1], profile.get(k).copied().unwrap_or(*last));
319 let t = if b.0 > a.0 {
320 (y - a.0) / (b.0 - a.0)
321 } else {
322 0.0
323 };
324 Some(a.1 + t * (b.1 - a.1))
325}