Skip to main content

solow_viz/
lib.rs

1//! # solow-viz
2//!
3//! A dependency-light, general-purpose plotting backend that renders to SVG
4//! (with optional PNG raster export behind the `png` feature). It aims to be a
5//! small but genuinely useful, matplotlib-class engine: a [`Figure`] holding a
6//! grid of [`Axes`], each carrying its own data, scales, limits, legend, and
7//! styling.
8//!
9//! ## Quick start
10//!
11//! ```
12//! use solow_viz::Figure;
13//! let mut fig = Figure::new(640, 480);
14//! fig.axes().set_title("demo").plot(&[0.0, 1.0, 2.0, 3.0], &[0.0, 1.0, 4.0, 9.0]);
15//! let svg = fig.to_svg();
16//! assert!(svg.starts_with("<svg"));
17//! ```
18//!
19//! ## Subplots, legends, scales
20//!
21//! ```
22//! use solow_viz::{Figure, Scale, LegendLoc, Color, Marker, LineStyle};
23//! let mut fig = Figure::subplots(800, 600, 2, 2);
24//! fig.suptitle("gallery");
25//! let ax = fig.ax_at(0, 0).unwrap();
26//! ax.set_yscale(Scale::Log);
27//! ax.line(&[1.0, 2.0, 3.0], &[10.0, 100.0, 1000.0],
28//!         Color::BLUE, 2.0, LineStyle::Dashed, Marker::Circle, 1.0, Some("series"));
29//! ax.legend(LegendLoc::UpperLeft);
30//! assert_eq!(fig.naxes(), 4);
31//! ```
32//!
33//! The major capabilities:
34//!
35//! - **Layout**: [`Figure::subplots`] / [`Figure::ax_at`], a figure-level
36//!   [`Figure::suptitle`], per-axes labels/limits/scales.
37//! - **Scales**: linear, [`Scale::Log`], and [`Scale::Symlog`] with log tick
38//!   locators and formatters; [`Axes::set_xlim`]/[`Axes::set_ylim`];
39//!   [`Axes::invert_xaxis`]/[`Axes::invert_yaxis`].
40//! - **Plot types**: line, scatter, bar (vertical/horizontal/stacked/grouped),
41//!   histogram, error bars, step, fill-between/area, boxplot, violin, and a 2-D
42//!   heatmap with a colorbar.
43//! - **Styling**: [`Marker`]s, [`LineStyle`]s, per-series alpha, the `tab10`
44//!   color cycle plus sequential [`Colormap`]s, spines, tick direction,
45//!   font-size controls, annotations, and reference lines / spans.
46//! - **Legends**: per-series labels and an auto-placed [`Axes::legend`] box.
47
48mod axes;
49mod color;
50pub mod diagnostics;
51mod figure;
52mod render;
53mod scale;
54mod series;
55
56#[cfg(feature = "png")]
57mod png;
58
59pub use axes::{Annotation, Axes, LegendLoc, RefLine, RefSpan, Spines, TickDirection};
60pub use color::{Color, Colormap};
61pub use figure::Figure;
62pub use scale::Scale;
63pub use series::{BoxStats, LineStyle, Marker, Series, StepWhere, ViolinShape};
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    // ---- Backward-compatibility: the original API must still work. -------
70
71    #[test]
72    fn renders_line_plot() {
73        let mut fig = Figure::new(640, 480);
74        fig.axes()
75            .set_title("y = x^2")
76            .set_xlabel("x")
77            .set_ylabel("y")
78            .set_grid(true)
79            .plot(&[0.0, 1.0, 2.0, 3.0, 4.0], &[0.0, 1.0, 4.0, 9.0, 16.0]);
80        let svg = fig.to_svg();
81        assert!(svg.starts_with("<svg"));
82        assert!(svg.ends_with("</svg>"));
83        assert!(svg.contains("<polyline"));
84        assert!(svg.contains("y = x^2"));
85    }
86
87    #[test]
88    fn renders_scatter_and_bar_and_hist() {
89        let mut fig = Figure::new(500, 400);
90        {
91            let ax = fig.axes();
92            ax.scatter(&[1.0, 2.0, 3.0], &[2.0, 1.0, 3.0]);
93            ax.bar(&[1.0, 2.0, 3.0], &[3.0, 1.0, 2.0], 0.5);
94        }
95        let svg = fig.to_svg();
96        assert!(svg.contains("<circle"));
97        assert!(svg.contains("<rect"));
98
99        let mut h = Figure::new(500, 400);
100        h.axes().hist(&[0.1, 0.2, 0.2, 0.9, 1.0, 1.1, 1.1, 1.2], 4);
101        assert!(h.to_svg().contains("<rect"));
102    }
103
104    #[test]
105    fn nice_ticks_are_reasonable() {
106        let t = scale::nice_ticks(0.0, 9.7, 6);
107        assert!(t.first().unwrap() <= &0.0);
108        assert!(t.last().unwrap() >= &9.7);
109    }
110
111    // ---- Layout ----------------------------------------------------------
112
113    #[test]
114    fn subplots_2x2_emits_four_framed_axes() {
115        let mut fig = Figure::subplots(800, 600, 2, 2);
116        fig.suptitle("grid");
117        assert_eq!(fig.naxes(), 4);
118        assert_eq!(fig.shape(), (2, 2));
119        for i in 0..4 {
120            fig.ax(i)
121                .unwrap()
122                .plot(&[0.0, 1.0, 2.0], &[(i as f64), 1.0, 2.0]);
123        }
124        let svg = fig.to_svg();
125        // Each axes draws its own bottom spine line; with four axes there must
126        // be at least four <line> spines plus four polylines.
127        assert_eq!(svg.matches("<polyline").count(), 4);
128        // Four clip paths => four distinct framed axes regions.
129        assert_eq!(svg.matches("<clipPath").count(), 4);
130        assert!(svg.contains("grid"));
131    }
132
133    #[test]
134    fn ax_at_addresses_cells() {
135        let mut fig = Figure::subplots(400, 400, 2, 3);
136        assert!(fig.ax_at(1, 2).is_some());
137        assert!(fig.ax_at(2, 0).is_none());
138        assert!(fig.ax_at(0, 3).is_none());
139    }
140
141    // ---- Legends ---------------------------------------------------------
142
143    #[test]
144    fn legend_has_swatches() {
145        let mut fig = Figure::new(500, 400);
146        {
147            let ax = fig.axes();
148            ax.line(
149                &[0.0, 1.0, 2.0],
150                &[0.0, 1.0, 0.5],
151                Color::BLUE,
152                2.0,
153                LineStyle::Solid,
154                Marker::None,
155                1.0,
156                Some("alpha"),
157            );
158            ax.line(
159                &[0.0, 1.0, 2.0],
160                &[1.0, 0.5, 0.0],
161                Color::RED,
162                2.0,
163                LineStyle::Solid,
164                Marker::None,
165                1.0,
166                Some("beta"),
167            );
168            ax.legend(LegendLoc::UpperRight);
169        }
170        let svg = fig.to_svg();
171        assert!(svg.contains("class=\"legend\""));
172        assert_eq!(svg.matches("class=\"swatch\"").count(), 2);
173        assert!(svg.contains("alpha"));
174        assert!(svg.contains("beta"));
175    }
176
177    // ---- Scales ----------------------------------------------------------
178
179    #[test]
180    fn log_axis_has_log_spaced_ticks() {
181        let mut fig = Figure::new(500, 400);
182        fig.axes()
183            .set_yscale(Scale::Log)
184            .plot(&[1.0, 2.0, 3.0, 4.0], &[1.0, 10.0, 100.0, 1000.0]);
185        let svg = fig.to_svg();
186        // Decade labels for a 10^0..10^3 span.
187        assert!(svg.contains(">1<"));
188        assert!(svg.contains(">10<"));
189        assert!(svg.contains(">100<"));
190        assert!(svg.contains(">1000<"));
191    }
192
193    #[test]
194    fn log_ticks_are_decade_spaced() {
195        let t = Scale::Log.ticks(1.0, 1000.0, 6);
196        // Powers of ten only across multiple decades.
197        assert!(t.contains(&1.0));
198        assert!(t.contains(&10.0));
199        assert!(t.contains(&100.0));
200        assert!(t.contains(&1000.0));
201        // Ratios between consecutive ticks are ~10.
202        for w in t.windows(2) {
203            let r = w[1] / w[0];
204            assert!((r - 10.0).abs() < 1e-6, "ratio {r}");
205        }
206    }
207
208    #[test]
209    fn symlog_handles_sign_change() {
210        let s = Scale::Symlog { linthresh: 1.0 };
211        assert!(s.forward(-10.0) < 0.0);
212        assert!(s.forward(10.0) > 0.0);
213        assert_eq!(s.forward(0.0), 0.0);
214        let t = s.ticks(-100.0, 100.0, 6);
215        assert!(t.iter().any(|&v| v < 0.0));
216        assert!(t.iter().any(|&v| v > 0.0));
217        assert!(t.contains(&0.0));
218    }
219
220    #[test]
221    fn inverted_axes_flip_mapping() {
222        let mut fig = Figure::new(400, 400);
223        fig.axes()
224            .invert_yaxis()
225            .invert_xaxis()
226            .plot(&[0.0, 1.0], &[0.0, 1.0]);
227        // Just ensure it renders without panicking and produces a polyline.
228        assert!(fig.to_svg().contains("<polyline"));
229    }
230
231    // ---- Plot types ------------------------------------------------------
232
233    #[test]
234    fn errorbar_emits_caps_and_stems() {
235        let mut fig = Figure::new(500, 400);
236        fig.axes().errorbar(
237            &[1.0, 2.0, 3.0],
238            &[1.0, 2.0, 1.5],
239            &[0.2, 0.3, 0.1],
240            Color::BLUE,
241            Some("y"),
242        );
243        let svg = fig.to_svg();
244        // 3 stems + 6 caps + 3 point markers => plenty of lines and circles.
245        assert!(svg.matches("<line").count() >= 9);
246        assert!(svg.contains("<circle"));
247    }
248
249    #[test]
250    fn step_emits_polyline() {
251        let mut fig = Figure::new(500, 400);
252        fig.axes().step(
253            &[0.0, 1.0, 2.0, 3.0],
254            &[1.0, 3.0, 2.0, 4.0],
255            Color::GREEN,
256            StepWhere::Post,
257            Some("s"),
258        );
259        assert!(fig.to_svg().contains("<polyline"));
260    }
261
262    #[test]
263    fn fill_between_emits_path() {
264        let mut fig = Figure::new(500, 400);
265        let x = vec![0.0, 1.0, 2.0, 3.0];
266        let lo = vec![0.0, 0.5, 0.2, 0.8];
267        let hi = vec![1.0, 1.5, 1.2, 1.8];
268        fig.axes()
269            .fill_between(&x, &lo, &hi, Color::BLUE, 0.3, Some("band"));
270        let svg = fig.to_svg();
271        assert!(svg.contains("<path"));
272        assert!(svg.contains("fill-opacity=\"0.300\""));
273    }
274
275    #[test]
276    fn stacked_and_grouped_bars() {
277        let mut s = Figure::new(500, 400);
278        s.axes().bar_stacked(
279            &[1.0, 2.0, 3.0],
280            &[vec![1.0, 2.0, 1.0], vec![2.0, 1.0, 3.0]],
281            0.6,
282            &["lo", "hi"],
283        );
284        let svg = s.to_svg();
285        assert!(svg.matches("<rect").count() >= 6);
286
287        let mut g = Figure::new(500, 400);
288        g.axes().bar_grouped(
289            &[1.0, 2.0],
290            &[vec![1.0, 2.0], vec![2.0, 1.0], vec![1.5, 1.5]],
291            0.8,
292            &["a", "b", "c"],
293        );
294        assert!(g.to_svg().matches("<rect").count() >= 6);
295    }
296
297    #[test]
298    fn horizontal_bar() {
299        let mut fig = Figure::new(500, 400);
300        fig.axes().barh(
301            &[1.0, 2.0, 3.0],
302            &[3.0, 1.0, 2.0],
303            0.5,
304            Color::ORANGE,
305            Some("h"),
306        );
307        assert!(fig.to_svg().contains("<rect"));
308    }
309
310    #[test]
311    fn boxplot_has_box_median_and_whiskers() {
312        let mut fig = Figure::new(500, 400);
313        let a: Vec<f64> = (0..50)
314            .map(|i| (i as f64 * 0.37).sin() * 2.0 + 5.0)
315            .collect();
316        let b: Vec<f64> = (0..50)
317            .map(|i| (i as f64 * 0.21).cos() * 3.0 + 6.0)
318            .collect();
319        fig.axes().boxplot(&[a, b], &[1.0, 2.0]);
320        let svg = fig.to_svg();
321        // The box rect, the median line, and whisker lines must all be present.
322        assert!(svg.contains("<rect"));
323        assert!(svg.contains("class=\"median\""));
324        assert!(svg.contains("class=\"whisker\""));
325    }
326
327    #[test]
328    fn violin_emits_silhouette_path() {
329        let mut fig = Figure::new(500, 400);
330        let a: Vec<f64> = (0..80).map(|i| (i as f64 * 0.3).sin() * 2.0).collect();
331        fig.axes().violinplot(&[a], &[1.0]);
332        assert!(fig.to_svg().contains("<path"));
333    }
334
335    #[test]
336    fn heatmap_has_grid_of_rects_and_colorbar() {
337        let mut fig = Figure::new(500, 400);
338        let data: Vec<Vec<f64>> = (0..4)
339            .map(|r| (0..5).map(|c| (r * 5 + c) as f64).collect())
340            .collect();
341        fig.axes()
342            .heatmap(&data, Colormap::Viridis, (0.0, 5.0, 0.0, 4.0), true);
343        let svg = fig.to_svg();
344        // 4*5 = 20 cell rects, drawn with crispEdges, plus a colorbar group.
345        assert!(svg.matches("crispEdges").count() >= 20);
346        assert!(svg.contains("class=\"colorbar\""));
347    }
348
349    #[test]
350    fn viridis_endpoints() {
351        let lo = Colormap::Viridis.sample(0.0);
352        let hi = Colormap::Viridis.sample(1.0);
353        // Dark blue/purple low end, bright yellow high end.
354        assert_eq!(lo, Color(68, 1, 84));
355        assert_eq!(hi, Color(253, 231, 37));
356    }
357
358    #[test]
359    fn color_cycle_wraps_at_ten() {
360        assert_eq!(Color::cycle(0), Color::cycle(10));
361        assert_ne!(Color::cycle(0), Color::cycle(1));
362    }
363
364    // ---- Markers / line styles -------------------------------------------
365
366    #[test]
367    fn markers_and_dashes_render() {
368        let mut fig = Figure::new(500, 400);
369        fig.axes().line(
370            &[0.0, 1.0, 2.0],
371            &[0.0, 1.0, 0.0],
372            Color::PURPLE,
373            2.0,
374            LineStyle::Dashed,
375            Marker::Square,
376            0.7,
377            None,
378        );
379        let svg = fig.to_svg();
380        assert!(svg.contains("stroke-dasharray"));
381        assert!(svg.contains("stroke-opacity=\"0.700\""));
382        // Square marker => an extra <rect>.
383        assert!(svg.contains("<rect"));
384
385        // Each marker variant should produce some SVG geometry.
386        for m in [
387            Marker::Circle,
388            Marker::Triangle,
389            Marker::Cross,
390            Marker::Plus,
391            Marker::Diamond,
392        ] {
393            let mut f = Figure::new(200, 200);
394            f.axes()
395                .scatter_full(&[0.0, 1.0], &[0.0, 1.0], Color::RED, 4.0, m, 1.0, None);
396            let s = f.to_svg();
397            assert!(
398                s.contains("<circle")
399                    || s.contains("<polygon")
400                    || s.contains("<rect")
401                    || s.contains("<line")
402            );
403        }
404    }
405
406    // ---- Styling / annotations / reference marks -------------------------
407
408    #[test]
409    fn spines_can_be_disabled() {
410        let mut fig = Figure::new(400, 300);
411        fig.axes()
412            .set_spines(false, false, true, true)
413            .plot(&[0.0, 1.0], &[0.0, 1.0]);
414        let svg = fig.to_svg();
415        assert!(svg.contains("<polyline"));
416        // Bottom-left only: with grid off and no ticks-grid, spine lines exist
417        // but we can at least confirm rendering succeeds.
418        assert!(svg.contains("<line"));
419    }
420
421    #[test]
422    fn annotations_and_reflines_and_spans() {
423        let mut fig = Figure::new(500, 400);
424        {
425            let ax = fig.axes();
426            ax.plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
427            ax.annotate(1.0, 1.0, "peak");
428            ax.axhline(2.0, Color::GRAY, LineStyle::Dashed);
429            ax.axvline(1.5, Color::GRAY, LineStyle::Dotted);
430            ax.axhspan(0.5, 1.5, Color::BLUE, 0.1);
431            ax.axvspan(0.2, 0.4, Color::RED, 0.1);
432        }
433        let svg = fig.to_svg();
434        assert!(svg.contains("peak"));
435        assert!(svg.contains("stroke-dasharray"));
436        assert!(svg.contains("fill-opacity=\"0.100\""));
437    }
438
439    #[test]
440    fn font_sizes_apply() {
441        let mut fig = Figure::new(400, 300);
442        fig.axes()
443            .set_font_sizes(14.0, 16.0, 20.0)
444            .set_title("t")
445            .plot(&[0.0, 1.0], &[0.0, 1.0]);
446        let svg = fig.to_svg();
447        assert!(svg.contains("font-size=\"20\""));
448    }
449
450    #[test]
451    fn empty_figure_renders() {
452        let fig = Figure::new(300, 200);
453        let svg = fig.to_svg();
454        assert!(svg.starts_with("<svg"));
455        assert!(svg.ends_with("</svg>"));
456    }
457
458    // ---- PNG (feature-gated) ---------------------------------------------
459
460    #[cfg(feature = "png")]
461    #[test]
462    fn png_export_writes_valid_signature() {
463        let mut fig = Figure::new(320, 240);
464        fig.axes()
465            .set_title("png")
466            .plot(&[0.0, 1.0, 2.0, 3.0], &[0.0, 1.0, 4.0, 9.0]);
467        let bytes = fig.to_png(2.0).expect("rasterize");
468        // PNG 8-byte signature.
469        assert_eq!(
470            &bytes[..8],
471            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
472        );
473        assert!(bytes.len() > 100);
474
475        let dir = std::env::temp_dir();
476        let path = dir.join("solow_viz_png_test.png");
477        fig.save_png(&path, 1.0).expect("write png");
478        let on_disk = std::fs::read(&path).expect("read back");
479        assert_eq!(
480            &on_disk[..8],
481            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
482        );
483        let _ = std::fs::remove_file(&path);
484    }
485}