rizzma 1.14.1

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
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
//! The [`Collection`] artist: a batched scatter of markers at data offsets.
//!
//! Mirrors matplotlib's `PathCollection` for the scatter case. A single unit
//! marker [`Path`] (origin-centered, e.g. from [`MarkerStyle`](crate::artist::MarkerStyle))
//! is stamped once per offset, each placement scaled by a per-point size and
//! painted with a per-point face and edge color. The `facecolors`, `edgecolors`,
//! and `sizes` vectors broadcast: a length-1 vector applies to every point, and
//! a length-N vector applies element-wise (indexed modulo its length), matching
//! matplotlib's broadcasting.

use crate::core::color::{ColorScale, Rgba};
use crate::core::{Affine2D, Bbox, Path};
use crate::render::{GraphicsContext, JoinStyle, Renderer};

use crate::artist::{Artist, MarkerStyle};

/// matplotlib's default scatter face color (`C0`, a muted blue), used by
/// [`Collection::scatter`] when no explicit face colors are given.
const DEFAULT_FACECOLOR: Rgba = Rgba::new(0.121_568_63, 0.466_666_67, 0.705_882_35, 1.0);

/// The default marker size (in points) used by [`Collection::scatter`].
const DEFAULT_SIZE: f64 = 6.0;

/// A batched scatter of markers at data-space offsets.
///
/// Each entry of `offsets` (in data coordinates) places one copy of the unit
/// `marker` path, scaled by the matching entry of `sizes` and filled/stroked
/// with the matching `facecolors`/`edgecolors`. The color and size vectors
/// broadcast (see the module docs).
///
/// Drawing currently fans out to one [`Renderer::draw_path`] per point; a future
/// optimization is a single batched `draw_path_collection`.
#[derive(Debug, Clone, PartialEq)]
pub struct Collection {
    /// Marker positions in data space.
    offsets: Vec<[f64; 2]>,
    /// The unit marker path, origin-centered, spanning roughly `1.0` unit.
    marker: Path,
    /// Per-point marker scales (in points); broadcast over `offsets`.
    sizes: Vec<f64>,
    /// Per-point fill colors; broadcast over `offsets`.
    facecolors: Vec<Rgba>,
    /// Per-point edge (stroke) colors; broadcast over `offsets`. Empty means no
    /// edge is drawn.
    edgecolors: Vec<Rgba>,
    /// Edge width in points.
    linewidth: f64,
    /// How the edges' corners join: round by default, as matplotlib's
    /// collections join whatever the marker.
    join: JoinStyle,
    /// Whether the collection is drawn.
    visible: bool,
    /// Stacking order; higher draws on top.
    zorder: f64,
    /// Legend label, collected by
    /// [`Axes::legend_auto`](crate::figure::Axes::legend_auto); `None` for an
    /// anonymous collection.
    label: Option<String>,
    /// The mapping the face colors came from, for a colorbar; `None` when
    /// the colors were given directly.
    color_scale: Option<ColorScale>,
}

impl Collection {
    /// Construct a scatter [`Collection`] from data-space `offsets`.
    ///
    /// Defaults mirror matplotlib's `scatter`: a filled circle (`'o'`) marker,
    /// size `6.0`, a muted-blue face, no edge, `1.0`-point edge width with
    /// round joins, visible, and zorder `1.0`.
    #[must_use]
    pub fn scatter(offsets: Vec<[f64; 2]>) -> Self {
        let marker = MarkerStyle::from_char('o')
            .expect("'o' is a known marker")
            .path()
            .clone();
        Self {
            offsets,
            marker,
            sizes: vec![DEFAULT_SIZE],
            facecolors: vec![DEFAULT_FACECOLOR],
            edgecolors: Vec::new(),
            linewidth: 1.0,
            join: JoinStyle::Round,
            visible: true,
            zorder: 1.0,
            label: None,
            color_scale: None,
        }
    }

    /// The color mapping the face colors came from, when the collection was
    /// colormapped from data (e.g. by
    /// [`Axes::scatter_mapped`](crate::figure::Axes::scatter_mapped)).
    #[must_use]
    pub fn color_scale(&self) -> Option<&ColorScale> {
        self.color_scale.as_ref()
    }

    /// Record the color mapping the face colors came from.
    pub(crate) fn with_color_scale(mut self, scale: ColorScale) -> Self {
        self.color_scale = Some(scale);
        self
    }

    /// The legend label, if any.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Set the legend label in place. Labels are collected by
    /// [`Axes::legend_auto`](crate::figure::Axes::legend_auto), which keys a
    /// labelled collection with a sample of its marker; a label starting with
    /// `_` is kept on the collection but never shown in a legend, as in
    /// matplotlib.
    ///
    /// ```
    /// use rizzma::Figure;
    /// let mut fig = Figure::new(4.0, 3.0);
    /// let ax = fig.add_subplot(1, 1, 1);
    /// ax.scatter(&[1.0, 2.0], &[3.0, 4.0]).set_label("data");
    /// ax.plot(&[1.0, 2.0], &[3.0, 4.0]).set_label("model");
    /// ax.legend_auto();
    /// ```
    pub fn set_label(&mut self, label: impl Into<String>) -> &mut Self {
        self.label = Some(label.into());
        self
    }

    /// Set the legend label, returning `self` for chaining; see
    /// [`set_label`](Collection::set_label).
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.set_label(label);
        self
    }

    /// Set the unit marker path in place.
    ///
    /// ```
    /// use rizzma::artist::{Collection, MarkerStyle};
    /// let square = MarkerStyle::from_char('s').unwrap().path().clone();
    /// let mut c = Collection::scatter(vec![[0.0, 0.0]]);
    /// c.set_marker(square.clone());
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0]]).with_marker(square));
    /// ```
    pub fn set_marker(&mut self, marker: Path) -> &mut Self {
        self.marker = marker;
        self
    }

    /// Set the per-point marker sizes (in points) in place. The sizes
    /// broadcast over the offsets.
    ///
    /// ```
    /// use rizzma::artist::Collection;
    /// let mut c = Collection::scatter(vec![[0.0, 0.0], [1.0, 1.0]]);
    /// c.set_sizes(vec![4.0, 9.0]);
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0], [1.0, 1.0]]).with_sizes(vec![4.0, 9.0]));
    /// ```
    pub fn set_sizes(&mut self, sizes: Vec<f64>) -> &mut Self {
        self.sizes = sizes;
        self
    }

    /// Set the per-point fill colors in place. The colors broadcast over the
    /// offsets.
    ///
    /// ```
    /// use rizzma::Figure;
    /// use rizzma::core::color::Rgba;
    /// let mut fig = Figure::new(4.0, 3.0);
    /// let ax = fig.add_subplot(1, 1, 1);
    /// ax.scatter(&[1.0, 2.0], &[3.0, 4.0])
    ///     .set_facecolors(vec![Rgba::RED])
    ///     .set_sizes(vec![12.0]);
    /// ```
    pub fn set_facecolors(&mut self, facecolors: Vec<Rgba>) -> &mut Self {
        self.facecolors = facecolors;
        self
    }

    /// Set the per-point edge colors in place. An empty vector means no edge
    /// is drawn; otherwise the colors broadcast over the offsets.
    ///
    /// ```
    /// use rizzma::artist::Collection;
    /// use rizzma::core::color::Rgba;
    /// let mut c = Collection::scatter(vec![[0.0, 0.0]]);
    /// c.set_edgecolors(vec![Rgba::BLACK]);
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0]]).with_edgecolors(vec![Rgba::BLACK]));
    /// ```
    pub fn set_edgecolors(&mut self, edgecolors: Vec<Rgba>) -> &mut Self {
        self.edgecolors = edgecolors;
        self
    }

    /// Set the edge width in points in place.
    ///
    /// ```
    /// use rizzma::artist::Collection;
    /// let mut c = Collection::scatter(vec![[0.0, 0.0]]);
    /// c.set_linewidth(0.5);
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0]]).linewidth(0.5));
    /// ```
    pub fn set_linewidth(&mut self, linewidth: f64) -> &mut Self {
        self.linewidth = linewidth;
        self
    }

    /// Set how the edges' corners join in place: matplotlib's
    /// `set_joinstyle`. Collections join round by default.
    pub fn set_joinstyle(&mut self, join: JoinStyle) -> &mut Self {
        self.join = join;
        self
    }

    /// Set the stacking order in place; higher draws on top.
    ///
    /// ```
    /// use rizzma::artist::Collection;
    /// let mut c = Collection::scatter(vec![[0.0, 0.0]]);
    /// c.set_zorder(3.0);
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0]]).with_zorder(3.0));
    /// ```
    pub fn set_zorder(&mut self, zorder: f64) -> &mut Self {
        self.zorder = zorder;
        self
    }

    /// Show or hide the collection in place.
    ///
    /// ```
    /// use rizzma::artist::Collection;
    /// let mut c = Collection::scatter(vec![[0.0, 0.0]]);
    /// c.set_visible(false);
    /// assert_eq!(c, Collection::scatter(vec![[0.0, 0.0]]).with_visible(false));
    /// ```
    pub fn set_visible(&mut self, visible: bool) -> &mut Self {
        self.visible = visible;
        self
    }

    /// Set the unit marker path, returning `self` for chaining.
    #[must_use]
    pub fn with_marker(mut self, marker: Path) -> Self {
        self.set_marker(marker);
        self
    }

    /// Set the per-point marker sizes (in points), returning `self` for
    /// chaining. The sizes broadcast over the offsets.
    #[must_use]
    pub fn with_sizes(mut self, sizes: Vec<f64>) -> Self {
        self.set_sizes(sizes);
        self
    }

    /// Set the per-point fill colors, returning `self` for chaining. The colors
    /// broadcast over the offsets.
    #[must_use]
    pub fn with_facecolors(mut self, facecolors: Vec<Rgba>) -> Self {
        self.set_facecolors(facecolors);
        self
    }

    /// Set the per-point edge colors, returning `self` for chaining. An empty
    /// vector means no edge is drawn; otherwise the colors broadcast over the
    /// offsets.
    #[must_use]
    pub fn with_edgecolors(mut self, edgecolors: Vec<Rgba>) -> Self {
        self.set_edgecolors(edgecolors);
        self
    }

    /// Set the edge width in points, returning `self` for chaining.
    #[must_use]
    pub fn linewidth(mut self, linewidth: f64) -> Self {
        self.set_linewidth(linewidth);
        self
    }

    /// Set how the edges' corners join, returning `self` for chaining.
    #[must_use]
    pub fn with_joinstyle(mut self, join: JoinStyle) -> Self {
        self.set_joinstyle(join);
        self
    }

    /// Set the stacking order, returning `self` for chaining.
    #[must_use]
    pub fn with_zorder(mut self, zorder: f64) -> Self {
        self.set_zorder(zorder);
        self
    }

    /// Set whether the collection is drawn, returning `self` for chaining.
    #[must_use]
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.set_visible(visible);
        self
    }

    /// The legend key for this collection: its color (the first face color,
    /// else the first edge color) and a one-marker template drawn as the
    /// sample, as matplotlib's scatter legend handle does — the same marker and
    /// first face/edge colors, sized at the middle of the finite size range.
    /// `None` when the collection has neither a face nor an edge to show.
    pub(crate) fn legend_sample(&self) -> Option<(Rgba, Collection)> {
        let face = self.facecolors.first().copied();
        let edge = self.edgecolors.first().copied();
        let color = face.or(edge)?;
        let (lo, hi) = self
            .sizes
            .iter()
            .copied()
            .filter(|s| s.is_finite())
            .fold(None, |range: Option<(f64, f64)>, s| {
                Some(range.map_or((s, s), |(lo, hi)| (lo.min(s), hi.max(s))))
            })
            .unwrap_or((DEFAULT_SIZE, DEFAULT_SIZE));
        let sample = Collection {
            offsets: Vec::new(),
            marker: self.marker.clone(),
            sizes: vec![0.5 * (lo + hi)],
            facecolors: face.into_iter().collect(),
            edgecolors: edge.into_iter().collect(),
            linewidth: self.linewidth,
            join: self.join,
            visible: true,
            zorder: self.zorder,
            label: None,
            color_scale: None,
        };
        Some((color, sample))
    }

    /// The fill color for point `i`, broadcasting over `facecolors`.
    ///
    /// Returns `None` only when `facecolors` is empty (no fill).
    fn facecolor_at(&self, i: usize) -> Option<Rgba> {
        broadcast(&self.facecolors, i)
    }

    /// The edge color for point `i`, broadcasting over `edgecolors`.
    ///
    /// Returns `None` when `edgecolors` is empty (no edge).
    fn edgecolor_at(&self, i: usize) -> Option<Rgba> {
        broadcast(&self.edgecolors, i)
    }

    /// The marker size for point `i`, broadcasting over `sizes`.
    ///
    /// Falls back to [`DEFAULT_SIZE`] when `sizes` is empty.
    fn size_at(&self, i: usize) -> f64 {
        broadcast(&self.sizes, i).unwrap_or(DEFAULT_SIZE)
    }

    /// Marker offsets in raw data coordinates.
    #[must_use]
    pub fn offsets(&self) -> &[[f64; 2]] {
        &self.offsets
    }

    /// Replace the marker offsets in place (for live/streaming updates),
    /// keeping the glyphs, sizes, colors, and z-order.
    pub fn set_offsets(&mut self, offsets: Vec<[f64; 2]>) -> &mut Self {
        self.offsets = offsets;
        self
    }

    /// Draw this collection with caller-supplied data offsets.
    ///
    /// The marker glyphs, sizes, colors, and z-order stay owned by the
    /// collection; only the data-space placement coordinates are substituted.
    /// This lets an owning axes pre-transform nonlinear-scale offsets while
    /// preserving point-size marker semantics.
    pub fn draw_with_offsets(
        &self,
        renderer: &mut dyn Renderer,
        offsets: &[[f64; 2]],
        transform: &Affine2D,
    ) {
        if !self.visible {
            return;
        }
        // One size, face and edge for every point: hand the renderer the
        // marker once and the points together, so a raster backend can
        // rasterize the marker a single time (matplotlib's `draw_markers`
        // path). Per-point styles draw point by point below.
        if self.sizes.len() <= 1 && self.facecolors.len() <= 1 && self.edgecolors.len() <= 1 {
            let size = renderer.points_to_pixels(self.size_at(0));
            let gc = GraphicsContext {
                line_width: self.linewidth,
                stroke: self.edgecolor_at(0),
                join: self.join,
                ..GraphicsContext::new()
            };
            let points: Vec<[f64; 2]> = offsets
                .iter()
                .copied()
                .filter(|[x, y]| x.is_finite() && y.is_finite())
                .collect();
            if !points.is_empty() {
                renderer.draw_markers(
                    &gc,
                    &self.marker,
                    &Affine2D::from_scale(size, size),
                    &Path::from_polyline(&points),
                    transform,
                    self.facecolor_at(0),
                );
            }
            return;
        }
        for (i, &[x, y]) in offsets.iter().enumerate() {
            if !x.is_finite() || !y.is_finite() {
                continue;
            }
            let size = renderer.points_to_pixels(self.size_at(i));
            // Markers are sized in points, not data units. Map the data offset
            // to device coordinates first, then stamp the unit marker there in
            // device-space pixels.
            let (dx, dy) = transform.transform_point((x, y));
            let point_transform = Affine2D::from_scale(size, size).translate(dx, dy);
            let edge = self.edgecolor_at(i);
            let gc = GraphicsContext {
                line_width: self.linewidth,
                stroke: edge,
                join: self.join,
                ..GraphicsContext::new()
            };
            renderer.draw_path(&gc, &self.marker, &point_transform, self.facecolor_at(i));
        }
    }
}

/// Index `values` at `i` modulo its length, broadcasting a length-1 vector to
/// every index. Returns `None` for an empty vector.
fn broadcast<T: Copy>(values: &[T], i: usize) -> Option<T> {
    if values.is_empty() {
        None
    } else {
        Some(values[i % values.len()])
    }
}

impl Artist for Collection {
    fn draw(&self, renderer: &mut dyn Renderer, transform: &Affine2D) {
        self.draw_with_offsets(renderer, &self.offsets, transform);
    }

    fn zorder(&self) -> f64 {
        self.zorder
    }

    fn visible(&self) -> bool {
        self.visible
    }

    fn data_extents(&self) -> Option<Bbox> {
        let mut xmin = f64::INFINITY;
        let mut ymin = f64::INFINITY;
        let mut xmax = f64::NEG_INFINITY;
        let mut ymax = f64::NEG_INFINITY;
        let mut any = false;
        for &[x, y] in &self.offsets {
            if !x.is_finite() || !y.is_finite() {
                continue;
            }
            xmin = xmin.min(x);
            ymin = ymin.min(y);
            xmax = xmax.max(x);
            ymax = ymax.max(y);
            any = true;
        }
        if any {
            Some(Bbox::from_extents(xmin, ymin, xmax, ymax))
        } else {
            None
        }
    }
}

#[cfg(feature = "portable")]
impl Collection {
    /// Flatten this collection into its wire form, banking bulk data as
    /// accessors.
    pub(crate) fn to_portable(
        &self,
        bank: &mut crate::portable::data::BankWriter,
    ) -> crate::portable::spec::CollectionSpec {
        let scale = crate::portable::spec::FlatScale::of(self.color_scale.as_ref());
        crate::portable::spec::CollectionSpec {
            offsets: bank.push_pairs(&self.offsets),
            marker: self.marker.to_portable(bank),
            sizes: bank.push_f64(&self.sizes),
            facecolors: self.facecolors.clone(),
            edgecolors: self.edgecolors.clone(),
            linewidth: self.linewidth,
            join: self.join,
            visible: self.visible,
            zorder: self.zorder,
            label: self.label.clone(),
            cmap: scale.cmap,
            norm: scale.norm,
            bad: scale.bad,
            over: scale.over,
            under: scale.under,
        }
    }

    /// Reconstruct a collection from its wire form during portable-figure
    /// import.
    pub(crate) fn from_portable(
        spec: &crate::portable::spec::CollectionSpec,
        reader: &crate::portable::data::BankReader<'_>,
    ) -> Result<Collection, crate::portable::PortableError> {
        Ok(Collection {
            offsets: reader.pairs(&spec.offsets)?,
            marker: Path::from_portable(&spec.marker, reader)?,
            sizes: reader.f64s(&spec.sizes)?,
            facecolors: spec.facecolors.clone(),
            edgecolors: spec.edgecolors.clone(),
            linewidth: spec.linewidth,
            join: spec.join,
            visible: spec.visible,
            zorder: spec.zorder,
            label: spec.label.clone(),
            color_scale: crate::portable::spec::FlatScale {
                cmap: spec.cmap.clone(),
                norm: spec.norm.clone(),
                bad: spec.bad,
                over: spec.over,
                under: spec.under,
            }
            .into_scale()?,
        })
    }
}

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

    /// A [`Renderer`] that records, per `draw_path` call, the resolved
    /// device-space translation alongside the fill and stroke colors.
    #[derive(Default)]
    struct MockRenderer {
        calls: Vec<Call>,
    }

    /// One recorded `draw_path` invocation.
    #[derive(Debug, Clone, Copy, PartialEq)]
    struct Call {
        translation: (f64, f64),
        scale: (f64, f64),
        fill: Option<Rgba>,
        stroke: Option<Rgba>,
    }

    impl Renderer for MockRenderer {
        fn draw_path(
            &mut self,
            gc: &GraphicsContext,
            _path: &Path,
            transform: &Affine2D,
            fill: Option<Rgba>,
        ) {
            let [a, _, _, d, e, f] = transform.matrix();
            self.calls.push(Call {
                translation: (e, f),
                scale: (a, d),
                fill,
                stroke: gc.stroke,
            });
        }

        fn canvas_size(&self) -> (f64, f64) {
            (100.0, 100.0)
        }

        fn points_to_pixels(&self, points: f64) -> f64 {
            points * 2.0
        }
    }

    #[test]
    fn scatter_draws_once_per_offset() {
        let offsets = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]];
        let coll = Collection::scatter(offsets);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        assert_eq!(r.calls.len(), 5);
    }

    #[test]
    fn single_facecolor_broadcasts_to_all() {
        let offsets = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]];
        let coll = Collection::scatter(offsets).with_facecolors(vec![Rgba::RED]);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        let fills: Vec<_> = r.calls.iter().map(|c| c.fill).collect();
        assert_eq!(fills, vec![Some(Rgba::RED); 3]);
    }

    #[test]
    fn per_point_facecolors_apply_elementwise() {
        let offsets = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]];
        let coll =
            Collection::scatter(offsets).with_facecolors(vec![Rgba::RED, Rgba::GREEN, Rgba::BLUE]);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        let fills: Vec<_> = r.calls.iter().map(|c| c.fill).collect();
        assert_eq!(
            fills,
            vec![Some(Rgba::RED), Some(Rgba::GREEN), Some(Rgba::BLUE)]
        );
    }

    #[test]
    fn edgecolors_drive_the_stroke() {
        let offsets = vec![[0.0, 0.0], [1.0, 0.0]];
        let coll = Collection::scatter(offsets).with_edgecolors(vec![Rgba::BLACK]);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        let strokes: Vec<_> = r.calls.iter().map(|c| c.stroke).collect();
        assert_eq!(strokes, vec![Some(Rgba::BLACK), Some(Rgba::BLACK)]);
    }

    #[test]
    fn no_edgecolors_means_no_stroke() {
        let offsets = vec![[0.0, 0.0]];
        let coll = Collection::scatter(offsets);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        assert_eq!(r.calls[0].stroke, None);
    }

    #[test]
    fn draw_places_markers_at_offsets() {
        let offsets = vec![[10.0, 20.0], [30.0, 40.0]];
        let coll = Collection::scatter(offsets);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        let translations: Vec<_> = r.calls.iter().map(|c| c.translation).collect();
        assert_eq!(translations, vec![(10.0, 20.0), (30.0, 40.0)]);
    }

    #[test]
    fn marker_size_is_in_device_points_not_data_units() {
        let coll = Collection::scatter(vec![[2.0, 3.0]]).with_sizes(vec![5.0]);
        let data_to_device = Affine2D::from_scale(10.0, 20.0).translate(1.0, 2.0);
        let mut r = MockRenderer::default();

        coll.draw(&mut r, &data_to_device);

        assert_eq!(r.calls.len(), 1);
        // Offset follows the full data transform.
        assert_eq!(r.calls[0].translation, (21.0, 62.0));
        // Size follows renderer points-to-pixels only: 5 pt * 2 px/pt = 10 px,
        // not the data transform's 10x/20x scale.
        assert_eq!(r.calls[0].scale, (10.0, 10.0));
    }

    #[test]
    fn invisible_collection_draws_nothing() {
        let coll = Collection::scatter(vec![[0.0, 0.0]]).with_visible(false);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        assert!(r.calls.is_empty());
    }

    #[test]
    fn with_zorder_sets_trait_zorder() {
        let coll = Collection::scatter(vec![[0.0, 0.0]]).with_zorder(9.0);
        assert_eq!(coll.zorder(), 9.0);
    }

    #[test]
    fn nan_offset_is_skipped_when_drawing() {
        let offsets = vec![[0.0, 0.0], [f64::NAN, 1.0], [2.0, 2.0]];
        let coll = Collection::scatter(offsets);
        let mut r = MockRenderer::default();
        coll.draw(&mut r, &Affine2D::identity());
        assert_eq!(r.calls.len(), 2);
    }

    #[test]
    fn data_extents_covers_offsets_ignoring_nan() {
        let offsets = vec![[1.0, -1.0], [f64::NAN, 5.0], [3.0, 4.0]];
        let coll = Collection::scatter(offsets);
        let e = coll.data_extents().expect("non-empty");
        assert_eq!(e.xmin(), 1.0);
        assert_eq!(e.xmax(), 3.0);
        assert_eq!(e.ymin(), -1.0);
        assert_eq!(e.ymax(), 4.0);
    }

    #[test]
    fn data_extents_empty_is_none() {
        let coll = Collection::scatter(vec![]);
        assert!(coll.data_extents().is_none());
    }

    #[test]
    fn default_zorder_is_one() {
        let coll = Collection::scatter(vec![[0.0, 0.0]]);
        assert_eq!(coll.zorder(), 1.0);
    }

    #[test]
    fn setters_restyle_in_place_without_copying_offsets() {
        let n = 1_000_000;
        let offsets: Vec<[f64; 2]> = (0..n).map(|i| [i as f64, (i % 7) as f64]).collect();
        let mut coll = Collection::scatter(offsets);
        let before = coll.offsets().as_ptr();
        let square = MarkerStyle::from_char('s').unwrap().path().clone();
        coll.set_marker(square)
            .set_sizes(vec![2.0])
            .set_facecolors(vec![Rgba::RED])
            .set_edgecolors(vec![Rgba::BLACK])
            .set_linewidth(0.25)
            .set_zorder(4.0)
            .set_visible(false);
        assert_eq!(coll.offsets().as_ptr(), before);
        assert_eq!(coll.offsets().len(), n);
        assert_eq!(coll.zorder(), 4.0);
        assert!(!coll.visible());
    }
}