plotkit-core 0.1.1

Core types and logic for the plotkit plotting library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Artist types -- data + styling for each visual chart element.
//!
//! Artists are the data-carrying objects stored in [`Axes`]. Each artist type
//! holds the data-space geometry and styling for one visual element. When the
//! figure is rendered, the renderer iterates over the artist list and draws
//! each one according to its variant.
//!
//! [`Axes`]: crate::axes::Axes
//!
//! # Variants
//!
//! | Variant          | Description                                     |
//! |------------------|-------------------------------------------------|
//! | [`Line`]         | A polyline connecting (x, y) points.             |
//! | [`Scatter`]      | Individual markers at (x, y) positions.          |
//! | [`Bar`]          | Vertical or horizontal bars over categories.     |
//! | [`Histogram`]    | Binned frequency distribution of a single series.|
//! | [`FillBetween`]  | Shaded region between two y-series.              |
//!
//! [`Line`]: Artist::Line
//! [`Scatter`]: Artist::Scatter
//! [`Bar`]: Artist::Bar
//! [`Histogram`]: Artist::Histogram
//! [`FillBetween`]: Artist::FillBetween

use crate::primitives::Color;
use crate::series::{Categories, Series};
use crate::theme::{LineStyle, Marker};

// ---------------------------------------------------------------------------
// Artist enum
// ---------------------------------------------------------------------------

/// A visual element drawn on an axes.
///
/// `Artist` is the primary unit of chart content. Each variant wraps a
/// concrete artist struct that stores the data, colors, and styling needed
/// to render one visual element. The enum provides convenience accessors
/// ([`label`](Artist::label), [`color`](Artist::color),
/// [`data_bounds`](Artist::data_bounds)) that dispatch to the inner type.
#[derive(Debug, Clone)]
pub enum Artist {
    /// A line chart connecting (x, y) points.
    Line(LineArtist),
    /// A scatter plot of individual points.
    Scatter(ScatterArtist),
    /// A bar chart (vertical or horizontal).
    Bar(BarArtist),
    /// A histogram (binned frequency distribution).
    Histogram(HistArtist),
    /// A filled region between two y-series sharing a common x-series.
    FillBetween(FillBetweenArtist),
}

impl Artist {
    /// Returns the legend label for this artist, if one has been set.
    ///
    /// The legend renderer uses this to decide which artists appear in the
    /// legend. Artists without a label are silently skipped.
    pub fn label(&self) -> Option<&str> {
        match self {
            Artist::Line(a) => a.label.as_deref(),
            Artist::Scatter(a) => a.label.as_deref(),
            Artist::Bar(a) => a.label.as_deref(),
            Artist::Histogram(a) => a.label.as_deref(),
            Artist::FillBetween(a) => a.label.as_deref(),
        }
    }

    /// Returns the primary color of this artist.
    ///
    /// Used by the legend to draw a color swatch next to the label, and by
    /// any other component that needs to identify an artist's color (e.g.
    /// tooltip rendering).
    pub fn color(&self) -> Color {
        match self {
            Artist::Line(a) => a.color,
            Artist::Scatter(a) => a.color,
            Artist::Bar(a) => a.color,
            Artist::Histogram(a) => a.color,
            Artist::FillBetween(a) => a.color,
        }
    }

    /// Returns the data-space bounding box as `(xmin, xmax, ymin, ymax)`.
    ///
    /// The axes autoscaling logic calls this on every artist to compute the
    /// tightest axis limits that contain all visible data. If a series is
    /// empty or contains no finite values, the corresponding min/max pair
    /// falls back to `(0.0, 1.0)` so that the axes always have a non-zero
    /// extent.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        match self {
            Artist::Line(a) => a.data_bounds(),
            Artist::Scatter(a) => a.data_bounds(),
            Artist::Bar(a) => a.data_bounds(),
            Artist::Histogram(a) => a.data_bounds(),
            Artist::FillBetween(a) => a.data_bounds(),
        }
    }
}

// ---------------------------------------------------------------------------
// Helper: safe bounds with fallback
// ---------------------------------------------------------------------------

/// Returns `(min, max)` of the finite values in `series`, falling back to
/// `(fallback_min, fallback_max)` when the series is empty or entirely
/// non-finite.
fn series_bounds_or(series: &Series, fallback_min: f64, fallback_max: f64) -> (f64, f64) {
    match series.bounds() {
        Some((lo, hi)) => (lo, hi),
        None => (fallback_min, fallback_max),
    }
}

// ---------------------------------------------------------------------------
// LineArtist
// ---------------------------------------------------------------------------

/// A line chart connecting a sequence of (x, y) data points.
///
/// The `x` and `y` series must have the same length. Points are drawn in
/// order, producing a single connected polyline with the configured stroke
/// style.
#[derive(Debug, Clone)]
pub struct LineArtist {
    /// X-coordinates of the data points.
    pub x: Series,
    /// Y-coordinates of the data points.
    pub y: Series,
    /// Stroke color of the line.
    pub color: Color,
    /// Stroke width in pixels.
    pub width: f64,
    /// Stroke pattern (solid, dashed, dotted, dash-dot).
    pub style: LineStyle,
    /// Optional legend label. When `Some`, the line appears in the legend.
    pub label: Option<String>,
    /// Opacity from 0.0 (fully transparent) to 1.0 (fully opaque).
    pub alpha: f64,
}

impl LineArtist {
    /// Computes the data-space bounding box `(xmin, xmax, ymin, ymax)`.
    ///
    /// Falls back to `(0.0, 1.0)` on each axis when the corresponding
    /// series contains no finite values.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        let (xmin, xmax) = series_bounds_or(&self.x, 0.0, 1.0);
        let (ymin, ymax) = series_bounds_or(&self.y, 0.0, 1.0);
        (xmin, xmax, ymin, ymax)
    }
}

// ---------------------------------------------------------------------------
// ScatterArtist
// ---------------------------------------------------------------------------

/// A scatter plot rendering individual markers at (x, y) positions.
///
/// Each data point is drawn as a marker whose shape, size, and color can be
/// configured. An optional per-point `colors` vector overrides the uniform
/// `color` field, enabling colormap-based visualizations.
#[derive(Debug, Clone)]
pub struct ScatterArtist {
    /// X-coordinates of the data points.
    pub x: Series,
    /// Y-coordinates of the data points.
    pub y: Series,
    /// Default marker color (used when `colors` is `None`).
    pub color: Color,
    /// Marker shape.
    pub marker: Marker,
    /// Marker diameter in pixels.
    pub size: f64,
    /// Optional legend label. When `Some`, the scatter appears in the legend.
    pub label: Option<String>,
    /// Opacity from 0.0 (fully transparent) to 1.0 (fully opaque).
    pub alpha: f64,
    /// Optional per-point colors for colormap-driven scatter plots.
    ///
    /// When set, `colors.len()` must equal `x.len()` (and `y.len()`). Each
    /// entry overrides `color` for the corresponding data point.
    pub colors: Option<Vec<Color>>,
}

impl ScatterArtist {
    /// Computes the data-space bounding box `(xmin, xmax, ymin, ymax)`.
    ///
    /// Falls back to `(0.0, 1.0)` on each axis when the corresponding
    /// series contains no finite values.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        let (xmin, xmax) = series_bounds_or(&self.x, 0.0, 1.0);
        let (ymin, ymax) = series_bounds_or(&self.y, 0.0, 1.0);
        (xmin, xmax, ymin, ymax)
    }
}

// ---------------------------------------------------------------------------
// BarArtist
// ---------------------------------------------------------------------------

/// A bar chart rendering vertical or horizontal bars over categorical data.
///
/// Categories are placed at integer positions `0, 1, 2, ...` on the
/// category axis, with each bar centered on its position. The `bar_width`
/// field controls the fraction of the inter-category spacing that the bar
/// occupies (1.0 = bars touching, 0.5 = half-width with gaps).
#[derive(Debug, Clone)]
pub struct BarArtist {
    /// Category labels for the bar axis.
    pub categories: Categories,
    /// Bar heights (or lengths, for horizontal bars).
    pub heights: Series,
    /// Fill color of the bars.
    pub color: Color,
    /// Optional legend label. When `Some`, the bar series appears in the legend.
    pub label: Option<String>,
    /// Opacity from 0.0 (fully transparent) to 1.0 (fully opaque).
    pub alpha: f64,
    /// When `true`, bars extend horizontally (categories on the y-axis).
    pub horizontal: bool,
    /// Bar width as a fraction of the category spacing (0.0, 1.0].
    pub bar_width: f64,
}

impl BarArtist {
    /// Computes the data-space bounding box `(xmin, xmax, ymin, ymax)`.
    ///
    /// For vertical bars, the x-axis spans from `-0.5` to `n - 0.5` (where
    /// `n` is the number of categories) so that bars are centered on integer
    /// positions. The y-axis spans from `0.0` to the tallest bar, with a
    /// fallback of `(0.0, 1.0)` when the heights series is empty.
    ///
    /// For horizontal bars the axes are transposed: the y-axis holds the
    /// category positions and the x-axis holds the bar lengths.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        let n = self.categories.len() as f64;

        // Determine the extent along the value axis (heights / lengths).
        let height_min = self.heights.min().unwrap_or(0.0).min(0.0);
        let height_max = self.heights.max().unwrap_or(1.0);

        // Category axis runs from -0.5 to n-0.5 so bars are centered on 0..n-1.
        let cat_min = -0.5;
        let cat_max = if n > 0.0 { n - 0.5 } else { 0.5 };

        if self.horizontal {
            // Horizontal bars: x = value axis, y = category axis.
            (height_min, height_max, cat_min, cat_max)
        } else {
            // Vertical bars: x = category axis, y = value axis.
            (cat_min, cat_max, height_min, height_max)
        }
    }
}

// ---------------------------------------------------------------------------
// HistArtist
// ---------------------------------------------------------------------------

/// A histogram showing the frequency distribution of a single data series.
///
/// The raw data is retained in `data`, but the binning results (`bin_edges`
/// and `counts`) are expected to be pre-computed when the artist is created
/// (typically by the histogram chart builder). This avoids re-binning during
/// every render pass.
///
/// When `density` is `true`, the `counts` vector stores probability density
/// values (each count divided by `n * bin_width`) rather than raw counts, so
/// that the total area under the histogram integrates to 1.0.
#[derive(Debug, Clone)]
pub struct HistArtist {
    /// The original (un-binned) data values.
    pub data: Series,
    /// The requested number of bins (used for display/debugging; the actual
    /// bin count is `bin_edges.len() - 1`).
    pub bins: usize,
    /// Sorted bin edges of length `bins + 1`. The i-th bin spans
    /// `[bin_edges[i], bin_edges[i+1])`.
    pub bin_edges: Vec<f64>,
    /// The count (or density) for each bin. Length equals `bin_edges.len() - 1`.
    pub counts: Vec<f64>,
    /// Fill color of the histogram bars.
    pub color: Color,
    /// Optional legend label. When `Some`, the histogram appears in the legend.
    pub label: Option<String>,
    /// Opacity from 0.0 (fully transparent) to 1.0 (fully opaque).
    pub alpha: f64,
    /// When `true`, `counts` stores probability density instead of raw counts.
    pub density: bool,
}

impl HistArtist {
    /// Computes the data-space bounding box `(xmin, xmax, ymin, ymax)`.
    ///
    /// The x-axis spans from the first bin edge to the last bin edge. The
    /// y-axis spans from `0.0` to the tallest bin count (or density value).
    /// Returns `(0.0, 1.0, 0.0, 1.0)` when there are no bin edges.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        if self.bin_edges.len() < 2 {
            return (0.0, 1.0, 0.0, 1.0);
        }

        // x-axis: first edge to last edge.
        let xmin = self.bin_edges[0];
        let xmax = self.bin_edges[self.bin_edges.len() - 1];

        // y-axis: 0 to tallest bin.
        let ymax = self
            .counts
            .iter()
            .copied()
            .filter(|v| v.is_finite())
            .fold(0.0_f64, f64::max);

        // Guarantee a non-zero y extent so the axes are always drawable.
        let ymax = if ymax <= 0.0 { 1.0 } else { ymax };

        (xmin, xmax, 0.0, ymax)
    }
}

// ---------------------------------------------------------------------------
// FillBetweenArtist
// ---------------------------------------------------------------------------

/// A filled region between two y-series that share a common x-series.
///
/// The renderer draws a closed polygon connecting `(x, y1)` forward and
/// `(x, y2)` backward, then fills it with the configured color and opacity.
/// This is commonly used for confidence bands, area charts, and shaded
/// difference regions.
#[derive(Debug, Clone)]
pub struct FillBetweenArtist {
    /// X-coordinates shared by both y-series.
    pub x: Series,
    /// Y-coordinates of the first boundary curve.
    pub y1: Series,
    /// Y-coordinates of the second boundary curve.
    pub y2: Series,
    /// Fill color of the shaded region.
    pub color: Color,
    /// Optional legend label. When `Some`, the fill region appears in the legend.
    pub label: Option<String>,
    /// Opacity from 0.0 (fully transparent) to 1.0 (fully opaque).
    pub alpha: f64,
}

impl FillBetweenArtist {
    /// Computes the data-space bounding box `(xmin, xmax, ymin, ymax)`.
    ///
    /// The x-bounds come from the shared `x` series. The y-bounds are the
    /// union of `y1` and `y2` (i.e. the overall min and max across both
    /// boundary curves). Falls back to `(0.0, 1.0)` on any axis that has
    /// no finite values.
    pub fn data_bounds(&self) -> (f64, f64, f64, f64) {
        let (xmin, xmax) = series_bounds_or(&self.x, 0.0, 1.0);

        // Union the y-bounds of both boundary series.
        let y1_min = self.y1.min();
        let y2_min = self.y2.min();
        let y1_max = self.y1.max();
        let y2_max = self.y2.max();

        let ymin = match (y1_min, y2_min) {
            (Some(a), Some(b)) => a.min(b),
            (Some(a), None) => a,
            (None, Some(b)) => b,
            (None, None) => 0.0,
        };

        let ymax = match (y1_max, y2_max) {
            (Some(a), Some(b)) => a.max(b),
            (Some(a), None) => a,
            (None, Some(b)) => b,
            (None, None) => 1.0,
        };

        (xmin, xmax, ymin, ymax)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper: build a simple `LineArtist` for testing.
    fn sample_line() -> LineArtist {
        LineArtist {
            x: Series::new(vec![1.0, 2.0, 3.0]),
            y: Series::new(vec![10.0, 20.0, 30.0]),
            color: Color::TAB_BLUE,
            width: 1.5,
            style: LineStyle::Solid,
            label: Some("line".to_string()),
            alpha: 1.0,
        }
    }

    /// Helper: build a simple `ScatterArtist` for testing.
    fn sample_scatter() -> ScatterArtist {
        ScatterArtist {
            x: Series::new(vec![0.0, 5.0, 10.0]),
            y: Series::new(vec![-1.0, 0.0, 1.0]),
            color: Color::TAB_ORANGE,
            marker: Marker::Circle,
            size: 6.0,
            label: None,
            alpha: 0.8,
            colors: None,
        }
    }

    /// Helper: build a simple `BarArtist` for testing.
    fn sample_bar() -> BarArtist {
        BarArtist {
            categories: Categories::new(vec!["A".into(), "B".into(), "C".into()]),
            heights: Series::new(vec![4.0, 7.0, 2.0]),
            color: Color::TAB_GREEN,
            label: Some("bars".to_string()),
            alpha: 1.0,
            horizontal: false,
            bar_width: 0.8,
        }
    }

    /// Helper: build a simple `HistArtist` for testing.
    fn sample_hist() -> HistArtist {
        HistArtist {
            data: Series::new(vec![1.0, 2.0, 2.5, 3.0, 3.5, 4.0]),
            bins: 3,
            bin_edges: vec![1.0, 2.0, 3.0, 4.0],
            counts: vec![1.0, 2.0, 3.0],
            color: Color::TAB_RED,
            label: Some("hist".to_string()),
            alpha: 0.7,
            density: false,
        }
    }

    /// Helper: build a simple `FillBetweenArtist` for testing.
    fn sample_fill_between() -> FillBetweenArtist {
        FillBetweenArtist {
            x: Series::new(vec![0.0, 1.0, 2.0]),
            y1: Series::new(vec![1.0, 3.0, 2.0]),
            y2: Series::new(vec![0.0, 1.0, 0.5]),
            color: Color::TAB_PURPLE,
            label: Some("fill".to_string()),
            alpha: 0.3,
        }
    }

    // -- Artist enum dispatch -----------------------------------------------

    #[test]
    fn artist_label_returns_inner_label() {
        let a = Artist::Line(sample_line());
        assert_eq!(a.label(), Some("line"));

        let a = Artist::Scatter(sample_scatter());
        assert_eq!(a.label(), None);

        let a = Artist::Bar(sample_bar());
        assert_eq!(a.label(), Some("bars"));

        let a = Artist::Histogram(sample_hist());
        assert_eq!(a.label(), Some("hist"));

        let a = Artist::FillBetween(sample_fill_between());
        assert_eq!(a.label(), Some("fill"));
    }

    #[test]
    fn artist_color_returns_inner_color() {
        assert_eq!(Artist::Line(sample_line()).color(), Color::TAB_BLUE);
        assert_eq!(Artist::Scatter(sample_scatter()).color(), Color::TAB_ORANGE);
        assert_eq!(Artist::Bar(sample_bar()).color(), Color::TAB_GREEN);
        assert_eq!(Artist::Histogram(sample_hist()).color(), Color::TAB_RED);
        assert_eq!(
            Artist::FillBetween(sample_fill_between()).color(),
            Color::TAB_PURPLE
        );
    }

    #[test]
    fn artist_data_bounds_dispatches_correctly() {
        let a = Artist::Line(sample_line());
        assert_eq!(a.data_bounds(), (1.0, 3.0, 10.0, 30.0));
    }

    // -- LineArtist ---------------------------------------------------------

    #[test]
    fn line_data_bounds_basic() {
        let a = sample_line();
        assert_eq!(a.data_bounds(), (1.0, 3.0, 10.0, 30.0));
    }

    #[test]
    fn line_data_bounds_empty_series() {
        let a = LineArtist {
            x: Series::new(vec![]),
            y: Series::new(vec![]),
            color: Color::BLACK,
            width: 1.0,
            style: LineStyle::Solid,
            label: None,
            alpha: 1.0,
        };
        assert_eq!(a.data_bounds(), (0.0, 1.0, 0.0, 1.0));
    }

    #[test]
    fn line_data_bounds_with_nan() {
        let a = LineArtist {
            x: Series::new(vec![f64::NAN, 2.0, 5.0]),
            y: Series::new(vec![1.0, f64::NAN, 3.0]),
            color: Color::BLACK,
            width: 1.0,
            style: LineStyle::Solid,
            label: None,
            alpha: 1.0,
        };
        assert_eq!(a.data_bounds(), (2.0, 5.0, 1.0, 3.0));
    }

    // -- ScatterArtist ------------------------------------------------------

    #[test]
    fn scatter_data_bounds_basic() {
        let a = sample_scatter();
        assert_eq!(a.data_bounds(), (0.0, 10.0, -1.0, 1.0));
    }

    #[test]
    fn scatter_data_bounds_empty() {
        let a = ScatterArtist {
            x: Series::new(vec![]),
            y: Series::new(vec![]),
            color: Color::BLACK,
            marker: Marker::Circle,
            size: 6.0,
            label: None,
            alpha: 1.0,
            colors: None,
        };
        assert_eq!(a.data_bounds(), (0.0, 1.0, 0.0, 1.0));
    }

    // -- BarArtist ----------------------------------------------------------

    #[test]
    fn bar_data_bounds_vertical() {
        let a = sample_bar();
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        assert!((xmin - (-0.5)).abs() < f64::EPSILON);
        assert!((xmax - 2.5).abs() < f64::EPSILON);
        assert!((ymin - 0.0).abs() < f64::EPSILON);
        assert!((ymax - 7.0).abs() < f64::EPSILON);
    }

    #[test]
    fn bar_data_bounds_horizontal() {
        let mut a = sample_bar();
        a.horizontal = true;
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        // Horizontal: x = value axis, y = category axis.
        assert!((xmin - 0.0).abs() < f64::EPSILON);
        assert!((xmax - 7.0).abs() < f64::EPSILON);
        assert!((ymin - (-0.5)).abs() < f64::EPSILON);
        assert!((ymax - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn bar_data_bounds_negative_heights() {
        let a = BarArtist {
            categories: Categories::new(vec!["A".into(), "B".into()]),
            heights: Series::new(vec![-3.0, 5.0]),
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
            horizontal: false,
            bar_width: 0.8,
        };
        let (_, _, ymin, ymax) = a.data_bounds();
        assert!((ymin - (-3.0)).abs() < f64::EPSILON);
        assert!((ymax - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn bar_data_bounds_empty() {
        let a = BarArtist {
            categories: Categories::new(vec![]),
            heights: Series::new(vec![]),
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
            horizontal: false,
            bar_width: 0.8,
        };
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        assert!((xmin - (-0.5)).abs() < f64::EPSILON);
        assert!((xmax - 0.5).abs() < f64::EPSILON);
        assert!((ymin - 0.0).abs() < f64::EPSILON);
        assert!((ymax - 1.0).abs() < f64::EPSILON);
    }

    // -- HistArtist ---------------------------------------------------------

    #[test]
    fn hist_data_bounds_basic() {
        let a = sample_hist();
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        assert!((xmin - 1.0).abs() < f64::EPSILON);
        assert!((xmax - 4.0).abs() < f64::EPSILON);
        assert!((ymin - 0.0).abs() < f64::EPSILON);
        assert!((ymax - 3.0).abs() < f64::EPSILON);
    }

    #[test]
    fn hist_data_bounds_empty_bins() {
        let a = HistArtist {
            data: Series::new(vec![]),
            bins: 0,
            bin_edges: vec![],
            counts: vec![],
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
            density: false,
        };
        assert_eq!(a.data_bounds(), (0.0, 1.0, 0.0, 1.0));
    }

    #[test]
    fn hist_data_bounds_single_edge_pair() {
        let a = HistArtist {
            data: Series::new(vec![1.0]),
            bins: 1,
            bin_edges: vec![0.5, 1.5],
            counts: vec![1.0],
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
            density: false,
        };
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        assert!((xmin - 0.5).abs() < f64::EPSILON);
        assert!((xmax - 1.5).abs() < f64::EPSILON);
        assert!((ymin - 0.0).abs() < f64::EPSILON);
        assert!((ymax - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn hist_data_bounds_all_zero_counts() {
        let a = HistArtist {
            data: Series::new(vec![]),
            bins: 2,
            bin_edges: vec![0.0, 1.0, 2.0],
            counts: vec![0.0, 0.0],
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
            density: false,
        };
        let (_, _, _, ymax) = a.data_bounds();
        // All-zero counts should produce a fallback ymax of 1.0.
        assert!((ymax - 1.0).abs() < f64::EPSILON);
    }

    // -- FillBetweenArtist --------------------------------------------------

    #[test]
    fn fill_between_data_bounds_basic() {
        let a = sample_fill_between();
        let (xmin, xmax, ymin, ymax) = a.data_bounds();
        assert!((xmin - 0.0).abs() < f64::EPSILON);
        assert!((xmax - 2.0).abs() < f64::EPSILON);
        assert!((ymin - 0.0).abs() < f64::EPSILON);
        assert!((ymax - 3.0).abs() < f64::EPSILON);
    }

    #[test]
    fn fill_between_data_bounds_empty() {
        let a = FillBetweenArtist {
            x: Series::new(vec![]),
            y1: Series::new(vec![]),
            y2: Series::new(vec![]),
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
        };
        assert_eq!(a.data_bounds(), (0.0, 1.0, 0.0, 1.0));
    }

    #[test]
    fn fill_between_data_bounds_y2_extends_beyond_y1() {
        let a = FillBetweenArtist {
            x: Series::new(vec![0.0, 1.0]),
            y1: Series::new(vec![1.0, 2.0]),
            y2: Series::new(vec![-5.0, 10.0]),
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
        };
        let (_, _, ymin, ymax) = a.data_bounds();
        assert!((ymin - (-5.0)).abs() < f64::EPSILON);
        assert!((ymax - 10.0).abs() < f64::EPSILON);
    }

    #[test]
    fn fill_between_data_bounds_one_series_empty() {
        // y1 has data, y2 is empty -- bounds should come from y1 alone.
        let a = FillBetweenArtist {
            x: Series::new(vec![0.0, 1.0]),
            y1: Series::new(vec![2.0, 8.0]),
            y2: Series::new(vec![]),
            color: Color::BLACK,
            label: None,
            alpha: 1.0,
        };
        let (_, _, ymin, ymax) = a.data_bounds();
        assert!((ymin - 2.0).abs() < f64::EPSILON);
        assert!((ymax - 8.0).abs() < f64::EPSILON);
    }
}