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 key_fill(&self) -> Option<((u8, u8, u8), f64)> {
103 Some((self.fill, self.alpha))
104 }
105
106 fn draw(
107 &self,
108 data: &DataFrame,
109 coord: &dyn Coord,
110 scales: &ScaleSet,
111 _theme: &Theme,
112 backend: &mut dyn DrawBackend,
113 ) -> Result<(), RenderError> {
114 let x_col = data
115 .column("x")
116 .ok_or(RenderError::MissingAesthetic("x".into()))?;
117 let y_col = data
118 .column("y")
119 .ok_or(RenderError::MissingAesthetic("y".into()))?;
120 let width_col = data
121 .column("violinwidth")
122 .ok_or(RenderError::MissingAesthetic("violinwidth".into()))?;
123 let fill_col = data.column("fill");
124
125 let plot_area = backend.plot_area();
126 let x_scale = scales.get(&Aesthetic::X);
127 let y_scale = scales.get(&Aesthetic::Y);
128
129 let x_is_discrete = x_scale.map(|s| s.is_discrete()).unwrap_or(false);
133 let max_half_width = if x_is_discrete {
134 let n = x_scale.map(|s| s.breaks().len()).unwrap_or(1);
135 0.75 / (n.max(1) as f64 * 2.5)
136 } else {
137 0.03
138 };
139
140 let x_mapper = super::support::XMapper::new(data, scales);
143 let density_col = data.column("density");
146 let n_col = data.column("n");
147 let max_of = |c: Option<&[crate::data::Value]>| {
148 c.map(|c| c.iter().filter_map(|v| v.as_f64()).fold(0.0_f64, f64::max))
149 .unwrap_or(0.0)
150 };
151 let (max_density, max_n) = (max_of(density_col), max_of(n_col));
152 let rel_width = |i: usize| -> f64 {
153 let own = width_col[i].as_f64().unwrap_or(0.0);
154 match self.scale {
155 ViolinScale::Width => own,
156 ViolinScale::Area => match density_col.and_then(|c| c[i].as_f64()) {
157 Some(d) if max_density > 0.0 => d / max_density,
158 _ => own,
159 },
160 ViolinScale::Count => match n_col.and_then(|c| c[i].as_f64()) {
161 Some(n) if max_n > 0.0 => own * n / max_n,
162 _ => own,
163 },
164 }
165 };
166 let series: Vec<Option<String>> = (0..data.nrows())
167 .map(|i| super::series_key(data, i))
168 .collect();
169
170 let mut order: Vec<String> = Vec::new();
175 let mut groups: HashMap<String, Vec<usize>> = HashMap::new();
176 for (i, xv) in x_col.iter().enumerate() {
177 let key = format!("{xv:?}\u{1f}{:?}", series[i]);
178 if !groups.contains_key(&key) {
179 order.push(key.clone());
180 groups.insert(key.clone(), Vec::new());
181 }
182 groups.get_mut(&key).unwrap().push(i);
183 }
184
185 for key in &order {
186 let idxs = &groups[key];
187 let first = idxs[0];
188 let nx = if x_scale.is_some() {
189 x_mapper.map(&x_col[first], first)
190 } else {
191 0.5
192 };
193 let max_half_width = max_half_width / x_mapper.slot_n(first);
194 let fill_color = fill_col
195 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first]))
196 .unwrap_or(self.fill);
197 let group = Some(super::tip_value(&x_col[first])).filter(|s| !s.is_empty());
198 super::set_mark(
199 backend,
200 group.clone(),
201 group,
202 super::series_key(data, first),
203 None,
204 );
205 super::set_mark_formatted(backend, scales, Some(&x_col[first]), &Aesthetic::Y, None);
206
207 let mut right_side: Vec<(f64, f64)> = Vec::with_capacity(idxs.len());
209 let mut left_side: Vec<(f64, f64)> = Vec::with_capacity(idxs.len());
210 for &i in idxs {
211 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
212 let half = rel_width(i) * max_half_width;
213 right_side.push(coord.transform((nx + half, ny), &plot_area));
214 left_side.push(coord.transform((nx - half, ny), &plot_area));
215 }
216
217 let mut polygon = right_side;
218 left_side.reverse();
219 polygon.extend(left_side);
220
221 if polygon.len() >= 3 {
222 backend.draw_polygon(
223 &polygon,
224 &RectStyle {
225 fill: Some(fill_color),
226 stroke: Some(self.color),
227 stroke_width: self.line_width,
228 alpha: self.alpha,
229 clip: true,
230 corner_radius: 0.0,
231 },
232 )?;
233 }
234
235 let quantiles = data
238 .column("quantiles")
239 .and_then(|c| c[first].as_str().map(str::to_string));
240 if let Some(q) = quantiles {
241 let mut profile: Vec<(f64, f64)> = idxs
242 .iter()
243 .filter_map(|&i| y_col[i].as_f64().map(|y| (y, rel_width(i))))
244 .collect();
245 profile.sort_by(|a, b| a.0.total_cmp(&b.0));
246 for qy in q.split(',').filter_map(|v| v.parse::<f64>().ok()) {
247 let Some(w) = interpolate(&profile, qy) else {
248 continue;
249 };
250 let half = w * max_half_width;
251 let ny = y_scale.map(|s| s.map(&crate::data::Value::Float(qy)));
252 let Some(ny) = ny else { continue };
253 backend.draw_line(
254 &[
255 coord.transform((nx - half, ny), &plot_area),
256 coord.transform((nx + half, ny), &plot_area),
257 ],
258 &LineStyle {
259 color: self.quantile_color.unwrap_or(self.color),
260 width: self.line_width.max(0.5),
261 alpha: 1.0,
262 linetype: self.quantile_linetype.clone(),
263 ..Default::default()
264 },
265 )?;
266 }
267 }
268 }
269 super::clear_mark(backend);
270
271 Ok(())
272 }
273
274 fn required_aes(&self) -> Vec<Aesthetic> {
275 vec![Aesthetic::X, Aesthetic::Y]
276 }
277
278 fn default_stat(&self) -> Box<dyn Stat> {
279 Box::new(StatYDensity {
280 trim: self.trim,
281 bw: self.bw,
282 adjust: self.adjust,
283 quantiles: self.quantiles.clone(),
284 ..Default::default()
285 })
286 }
287
288 fn default_position(&self) -> Box<dyn Position> {
290 Box::new(crate::position::dodge::PositionDodge)
291 }
292
293 fn default_params(&self) -> GeomParams {
294 GeomParams::default()
295 }
296
297 fn name(&self) -> &str {
298 "violin"
299 }
300
301 fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
302 if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
303 self.color = ink;
304 }
305 }
306
307 fn set_series_color(&mut self, color: (u8, u8, u8)) {
308 self.fill = color;
309 }
310}
311
312fn interpolate(profile: &[(f64, f64)], y: f64) -> Option<f64> {
314 let (first, last) = (profile.first()?, profile.last()?);
315 if y < first.0 || y > last.0 {
316 return None;
317 }
318 let k = profile.partition_point(|p| p.0 < y);
319 if k == 0 {
320 return Some(first.1);
321 }
322 let (a, b) = (profile[k - 1], profile.get(k).copied().unwrap_or(*last));
323 let t = if b.0 > a.0 {
324 (y - a.0) / (b.0 - a.0)
325 } else {
326 0.0
327 };
328 Some(a.1 + t * (b.1 - a.1))
329}