Skip to main content

crisol_plot/plot/
families.rs

1//! Chart families built on the core line, bar, and heatmap series: histograms, box
2//! plots, violins, hexbins, contours, polar, and Smith charts.
3
4use super::{Colormap, Series};
5
6/// A histogram of `values` as centered bars.
7pub fn histogram(name: impl Into<String>, values: &[f64], bins: usize) -> Series<'static> {
8    let bins = bins.max(1);
9    let finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
10    if finite.is_empty() {
11        return Series::bars(name, Vec::new());
12    }
13    let min = finite.iter().copied().fold(f64::INFINITY, f64::min);
14    let max = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
15    let span = (max - min).max(1e-12);
16    let width = span / bins as f64;
17    let mut counts = vec![0.0; bins];
18    for value in finite {
19        let index = (((value - min) / width) as usize).min(bins - 1);
20        counts[index] += 1.0;
21    }
22    let points: Vec<[f64; 2]> = counts
23        .iter()
24        .enumerate()
25        .map(|(index, count)| [min + (index as f64 + 0.5) * width, *count])
26        .collect();
27    Series::bars(name, points).bar_width(width * 0.9)
28}
29
30/// A histogram normalized so the bar areas sum to one; a density estimate appears as a
31/// line over the same bars.
32pub fn histogram_density(name: impl Into<String>, values: &[f64], bins: usize) -> Vec<Series<'static>> {
33    let bins = bins.max(1);
34    let finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
35    if finite.is_empty() {
36        return Vec::new();
37    }
38    let min = finite.iter().copied().fold(f64::INFINITY, f64::min);
39    let max = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
40    let span = (max - min).max(1e-12);
41    let width = span / bins as f64;
42    let mut counts = vec![0.0; bins];
43    for value in finite.iter().copied() {
44        counts[(((value - min) / width) as usize).min(bins - 1)] += 1.0;
45    }
46    let total = finite.len() as f64 * width;
47    let bars: Vec<[f64; 2]> = counts
48        .iter()
49        .enumerate()
50        .map(|(index, count)| [min + (index as f64 + 0.5) * width, count / total])
51        .collect();
52    let name = name.into();
53    let curve = Series::line(format!("{name} density"), bars.clone()).smooth(super::Smoothing::Spline);
54    vec![Series::bars(name, bars).bar_width(width * 0.9), curve]
55}
56
57/// A box plot at x = 0: box, median, whiskers, and caps.
58pub fn box_plot(name: impl Into<String>, values: &[f64]) -> Vec<Series<'static>> {
59    let mut sorted: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
60    if sorted.is_empty() {
61        return Vec::new();
62    }
63    sorted.sort_by(f64::total_cmp);
64    let quantile = |q: f64| {
65        let position = q.clamp(0.0, 1.0) * (sorted.len() - 1) as f64;
66        let low = position.floor() as usize;
67        let high = (low + 1).min(sorted.len() - 1);
68        sorted[low] + (sorted[high] - sorted[low]) * (position - low as f64)
69    };
70    let q1 = quantile(0.25);
71    let median = quantile(0.5);
72    let q3 = quantile(0.75);
73    let iqr = (q3 - q1).max(1e-12);
74    let low = sorted
75        .iter()
76        .copied()
77        .filter(|value| *value >= q1 - 1.5 * iqr)
78        .fold(q1, f64::min);
79    let high = sorted
80        .iter()
81        .copied()
82        .filter(|value| *value <= q3 + 1.5 * iqr)
83        .fold(q3, f64::max);
84    let name = name.into();
85    let half = 0.25;
86    let box_outline = vec![[-half, q1], [half, q1], [half, q3], [-half, q3], [-half, q1]];
87    vec![
88        Series::line(format!("{name} box"), box_outline),
89        Series::line(format!("{name} median"), vec![[-half, median], [half, median]]),
90        Series::line(format!("{name} whisker"), vec![[0.0, low], [0.0, high]]),
91        Series::line(format!("{name} low cap"), vec![[-half * 0.6, low], [half * 0.6, low]]),
92        Series::line(
93            format!("{name} high cap"),
94            vec![[-half * 0.6, high], [half * 0.6, high]],
95        ),
96    ]
97}
98
99/// A violin outline from a Gaussian kernel density estimate, centered at x = 0.
100pub fn violin(name: impl Into<String>, values: &[f64], samples: usize) -> Vec<Series<'static>> {
101    let finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
102    if finite.is_empty() {
103        return Vec::new();
104    }
105    let min = finite.iter().copied().fold(f64::INFINITY, f64::min);
106    let max = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
107    let span = (max - min).max(1e-12);
108    let bandwidth = (span / finite.len() as f64).sqrt().max(span / 100.0);
109    let samples = samples.clamp(16, 512);
110    let mut outline = Vec::with_capacity(samples * 2 + 1);
111    let mut density = Vec::with_capacity(samples);
112    for index in 0..samples {
113        let x = min + span * index as f64 / (samples - 1) as f64;
114        let value: f64 = finite
115            .iter()
116            .map(|sample| (-((x - sample) / bandwidth).powi(2) * 0.5).exp())
117            .sum::<f64>()
118            / finite.len() as f64;
119        density.push((x, value));
120    }
121    let peak = density.iter().map(|(_, value)| *value).fold(0.0, f64::max).max(1e-12);
122    for (x, value) in &density {
123        outline.push([value / peak * 0.35, *x]);
124    }
125    for (x, value) in density.iter().rev() {
126        outline.push([-value / peak * 0.35, *x]);
127    }
128    if let Some(first) = outline.first().copied() {
129        outline.push(first);
130    }
131    let name = name.into();
132    vec![
133        Series::line(format!("{name} violin"), outline),
134        Series::line(
135            format!("{name} median"),
136            vec![[-0.35, median_of(&finite)], [0.35, median_of(&finite)]],
137        ),
138    ]
139}
140
141fn median_of(sorted: &[f64]) -> f64 {
142    let mut values = sorted.to_vec();
143    values.sort_by(f64::total_cmp);
144    let middle = values.len() / 2;
145    if values.len().is_multiple_of(2) {
146        (values[middle - 1] + values[middle]) * 0.5
147    } else {
148        values[middle]
149    }
150}
151
152/// A regular hexbin/2D-density grid of `[x, y, count]` cells, ready for `Series::heatmap`.
153pub fn hexbin(name: impl Into<String>, points: &[[f64; 2]], bins: usize) -> Series<'static> {
154    let bins = bins.max(2);
155    let finite: Vec<[f64; 2]> = points
156        .iter()
157        .copied()
158        .filter(|point| point[0].is_finite() && point[1].is_finite())
159        .collect();
160    if finite.is_empty() {
161        return Series::heatmap(name, Vec::new());
162    }
163    let (min_x, max_x) = finite
164        .iter()
165        .fold((f64::INFINITY, f64::NEG_INFINITY), |(min, max), point| {
166            (min.min(point[0]), max.max(point[0]))
167        });
168    let (min_y, max_y) = finite
169        .iter()
170        .fold((f64::INFINITY, f64::NEG_INFINITY), |(min, max), point| {
171            (min.min(point[1]), max.max(point[1]))
172        });
173    let width = ((max_x - min_x) / bins as f64).max(1e-12);
174    let height = ((max_y - min_y) / bins as f64).max(1e-12);
175    let mut counts = vec![0.0; bins * bins];
176    for point in finite {
177        let x = (((point[0] - min_x) / width) as usize).min(bins - 1);
178        let y = (((point[1] - min_y) / height) as usize).min(bins - 1);
179        counts[y * bins + x] += 1.0;
180    }
181    let cells: Vec<[f64; 3]> = counts
182        .iter()
183        .enumerate()
184        .filter(|(_, count)| **count > 0.0)
185        .map(|(index, count)| {
186            let x = min_x + (index % bins) as f64 * width + width * 0.5;
187            let y = min_y + (index / bins) as f64 * height + height * 0.5;
188            [x, y, *count]
189        })
190        .collect();
191    let name = name.into();
192    Series::heatmap(name, cells)
193}
194
195/// A contour line of a regular grid at `level`, as one series with NaN breaks.
196pub fn contour(
197    name: impl Into<String>,
198    grid: &[Vec<f64>],
199    level: f64,
200    origin: [f64; 2],
201    step: [f64; 2],
202) -> Series<'static> {
203    let mut points: Vec<[f64; 2]> = Vec::new();
204    for row in 0..grid.len().saturating_sub(1) {
205        for column in 0..grid[row].len().saturating_sub(1) {
206            let values = [
207                grid[row][column],
208                grid[row][column + 1],
209                grid[row + 1][column + 1],
210                grid[row + 1][column],
211            ];
212            let corners = [
213                [origin[0] + column as f64 * step[0], origin[1] + row as f64 * step[1]],
214                [
215                    origin[0] + (column + 1) as f64 * step[0],
216                    origin[1] + row as f64 * step[1],
217                ],
218                [
219                    origin[0] + (column + 1) as f64 * step[0],
220                    origin[1] + (row + 1) as f64 * step[1],
221                ],
222                [
223                    origin[0] + column as f64 * step[0],
224                    origin[1] + (row + 1) as f64 * step[1],
225                ],
226            ];
227            let mut crossings = Vec::new();
228            for edge in 0..4 {
229                let next = (edge + 1) % 4;
230                let (a, b) = (values[edge], values[next]);
231                if (a < level && b >= level) || (a >= level && b < level) {
232                    let t = (level - a) / (b - a);
233                    let point = [
234                        corners[edge][0] + (corners[next][0] - corners[edge][0]) * t,
235                        corners[edge][1] + (corners[next][1] - corners[edge][1]) * t,
236                    ];
237                    crossings.push(point);
238                }
239            }
240            if crossings.len() >= 2 {
241                if !points.is_empty() {
242                    points.push([f64::NAN, f64::NAN]);
243                }
244                points.push(crossings[0]);
245                points.push(crossings[1]);
246            }
247        }
248    }
249    Series::line(name, points)
250}
251
252/// Convert polar samples `(theta, radius)` to a cartesian line.
253pub fn polar(name: impl Into<String>, theta: &[f64], radius: &[f64]) -> Series<'static> {
254    let points = theta
255        .iter()
256        .zip(radius)
257        .filter(|(theta, radius)| theta.is_finite() && radius.is_finite())
258        .map(|(theta, radius)| [radius * theta.cos(), radius * theta.sin()])
259        .collect::<Vec<_>>();
260    Series::line(name, points)
261}
262
263/// Convert impedance samples `(resistance, reactance)` to a Smith-chart reflection line.
264pub fn smith(name: impl Into<String>, resistance: &[f64], reactance: &[f64]) -> Series<'static> {
265    let points = resistance
266        .iter()
267        .zip(reactance)
268        .filter(|(resistance, reactance)| resistance.is_finite() && reactance.is_finite())
269        .map(|(resistance, reactance)| {
270            let (zr, zi) = (*resistance, *reactance);
271            let denominator = (zr + 1.0).powi(2) + zi * zi;
272            [
273                ((zr * zr + zi * zi - 1.0) / denominator.max(1e-12)),
274                (2.0 * zi / denominator.max(1e-12)),
275            ]
276        })
277        .collect::<Vec<_>>();
278    Series::line(name, points)
279}
280
281/// A colorbar widget for an existing colormap, drawn at the current cursor.
282pub fn show_colorbar(ui: &mut egui::Ui, colormap: Colormap, min: f64, max: f64, height: f32) {
283    let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, height), egui::Sense::hover());
284    let bands = 32;
285    let theme = crisol_ui_kit::theme::current(ui.ctx());
286    for index in 0..bands {
287        let t = index as f32 / (bands - 1) as f32;
288        let band = egui::Rect::from_min_size(
289            egui::pos2(
290                rect.left() + 4.0,
291                rect.bottom() - (index + 1) as f32 * rect.height() / bands as f32,
292            ),
293            egui::vec2(10.0, rect.height() / bands as f32 + 1.0),
294        );
295        ui.painter().rect_filled(band, 0.0, colormap.sample(1.0 - t, &theme));
296    }
297    ui.painter().text(
298        egui::pos2(rect.right() + 4.0, rect.top()),
299        egui::Align2::LEFT_TOP,
300        format!("{max:.3}"),
301        crisol_ui_kit::style::get(ui.ctx()).font(9.0),
302        ui.visuals().weak_text_color(),
303    );
304    ui.painter().text(
305        egui::pos2(rect.right() + 4.0, rect.bottom()),
306        egui::Align2::LEFT_BOTTOM,
307        format!("{min:.3}"),
308        crisol_ui_kit::style::get(ui.ctx()).font(9.0),
309        ui.visuals().weak_text_color(),
310    );
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn histogram_bars_sum_to_the_sample_count() {
319        let values = [0.1, 0.2, 0.25, 0.8, 0.95];
320        let series = histogram("h", &values, 5);
321        let total: f64 = series.data().iter().map(|point| point[1]).sum();
322        assert_eq!(total, values.len() as f64);
323    }
324
325    #[test]
326    fn box_and_violin_have_the_expected_parts() {
327        let values = [1.0, 2.0, 3.0, 4.0, 100.0];
328        assert_eq!(box_plot("b", &values).len(), 5);
329        assert_eq!(violin("v", &values, 32).len(), 2);
330    }
331
332    #[test]
333    fn hexbin_and_contour_produce_geometry() {
334        let points = [[0.0, 0.0], [0.1, 0.1], [1.0, 1.0]];
335        let hex = hexbin("h", &points, 4);
336        assert!(hex.cells().is_some_and(|cells| !cells.is_empty()));
337        let grid = vec![vec![0.0, 0.0, 0.0], vec![0.0, 1.0, 0.0], vec![0.0, 0.0, 0.0]];
338        let contour = contour("c", &grid, 0.5, [0.0, 0.0], [1.0, 1.0]);
339        assert!(contour.data().len() >= 2);
340    }
341
342    #[test]
343    fn polar_and_smith_map_domain_values() {
344        let polar = polar("p", &[0.0, std::f64::consts::FRAC_PI_2], &[1.0, 1.0]);
345        assert_eq!(polar.data()[0], [1.0, 0.0]);
346        let smith = smith("s", &[1.0], &[0.0]);
347        assert!((smith.data()[0][0] - 0.0).abs() < 1e-9);
348        assert!((smith.data()[0][1] - 0.0).abs() < 1e-9);
349    }
350}