Skip to content

VisPy 2 API Reference

The VisPy 2 package provides a high-level producer facade for GSP protocol scenes. 2D interaction is owned by canonical GSP View2D navigation, not by the removed legacy vispy2.axes pan/zoom helpers.

Overview

vispy2

VisPy2 experimental producer API.

Axes dataclass

Minimal axes object that produces GSP protocol visuals.

Source code in src/vispy2/protocol.py
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
@dataclass(slots=True)
class Axes:
    """Minimal axes object that produces GSP protocol visuals."""

    figure: Figure
    visuals: list[
        PointVisual
        | MarkerVisual
        | SegmentVisual
        | PathVisual
        | MeshVisual
        | ImageVisual
        | TextVisual
    ] = field(default_factory=list)
    panel: Panel = field(init=False)
    view: View2D = field(init=False)
    attachments: list[VisualAttachment] = field(default_factory=list)
    axis_guides: list[AxisGuide] = field(default_factory=list)
    panel_text_guides: list[PanelTextGuide] = field(default_factory=list)
    colorbar_guides: list[ColorbarGuide] = field(default_factory=list)

    def __post_init__(self) -> None:
        index = len(self.figure.axes) + 1
        panel_id = f"panel:{index}"
        view_id = f"view:{index}"
        self.panel = Panel(id=panel_id, figure_id=self.figure.id)
        self.view = View2D(id=view_id, panel_id=panel_id)
        self.axis_guides.extend(
            [
                AxisGuide(
                    id=f"guide:x-{index}",
                    view_id=view_id,
                    dimension=AxisDimension.X,
                    side=AxisSide.BOTTOM,
                ),
                AxisGuide(
                    id=f"guide:y-{index}",
                    view_id=view_id,
                    dimension=AxisDimension.Y,
                    side=AxisSide.LEFT,
                ),
            ]
        )

    def set_xlim(self, left: float, right: float) -> tuple[float, float]:
        """Set the semantic x range for this 2D view."""
        self.view = View2D(
            id=self.view.id,
            panel_id=self.view.panel_id,
            x_range=(float(left), float(right)),
            y_range=self.view.y_range,
            aspect_policy=self.view.aspect_policy,
        )
        return self.view.x_range

    def set_ylim(self, bottom: float, top: float) -> tuple[float, float]:
        """Set the semantic y range for this 2D view."""
        self.view = View2D(
            id=self.view.id,
            panel_id=self.view.panel_id,
            x_range=self.view.x_range,
            y_range=(float(bottom), float(top)),
            aspect_policy=self.view.aspect_policy,
        )
        return self.view.y_range

    def set_view2d(
        self,
        *,
        xlim: tuple[float, float] | None = None,
        ylim: tuple[float, float] | None = None,
        clip: bool | None = None,
    ) -> View2D:
        """Set deterministic S027 View2D state."""
        next_xlim = self.view.xlim if xlim is None else (float(xlim[0]), float(xlim[1]))
        next_ylim = self.view.ylim if ylim is None else (float(ylim[0]), float(ylim[1]))
        self.view = View2D(
            id=self.view.id,
            panel_id=self.view.panel_id,
            x_range=next_xlim,
            y_range=next_ylim,
            aspect_policy=self.view.aspect_policy,
            kind=self.view.kind,
            clip=self.view.clip if clip is None else bool(clip),
        )
        return self.view

    def get_xlim(self) -> tuple[float, float]:
        """Return the semantic x range for this 2D view."""
        return self.view.x_range

    def get_ylim(self) -> tuple[float, float]:
        """Return the semantic y range for this 2D view."""
        return self.view.y_range

    def set_xlabel(self, text: str | None) -> str | None:
        """Set the semantic x-axis label."""
        self._set_axis_guide(AxisDimension.X, label_text=text)
        return text

    def get_xlabel(self) -> str | None:
        """Return the semantic x-axis label."""
        return self._axis_guide(AxisDimension.X).label_text

    def set_ylabel(self, text: str | None) -> str | None:
        """Set the semantic y-axis label."""
        self._set_axis_guide(AxisDimension.Y, label_text=text)
        return text

    def get_ylabel(self) -> str | None:
        """Return the semantic y-axis label."""
        return self._axis_guide(AxisDimension.Y).label_text

    def set_title(self, text: str | None) -> str | None:
        """Set or clear the semantic panel title."""
        self.panel_text_guides = [
            guide
            for guide in self.panel_text_guides
            if guide.role != PanelTextRole.TITLE
        ]
        if text:
            self.panel_text_guides.append(
                PanelTextGuide(
                    id=f"guide:title-{self._index}",
                    panel_id=self.panel.id,
                    role=PanelTextRole.TITLE,
                    text=text,
                )
            )
        return text

    def get_title(self) -> str | None:
        """Return the semantic panel title, if any."""
        for guide in self.panel_text_guides:
            if guide.role == PanelTextRole.TITLE:
                return guide.text
        return None

    def set_xticks(
        self, ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None
    ) -> tuple[float, ...]:
        """Set explicit semantic x-axis tick values and optional labels."""
        values = _tick_values(ticks)
        self._set_axis_guide(
            AxisDimension.X, tick_spec=_explicit_tick_spec(values, labels)
        )
        return values

    def get_xticks(self) -> tuple[float, ...]:
        """Return explicit semantic x-axis ticks, or an empty tuple for non-explicit ticks."""
        spec = self._axis_guide(AxisDimension.X).tick_spec
        return spec.explicit_values if spec.kind == TickSpecKind.EXPLICIT else ()

    def set_yticks(
        self, ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None
    ) -> tuple[float, ...]:
        """Set explicit semantic y-axis tick values and optional labels."""
        values = _tick_values(ticks)
        self._set_axis_guide(
            AxisDimension.Y, tick_spec=_explicit_tick_spec(values, labels)
        )
        return values

    def get_yticks(self) -> tuple[float, ...]:
        """Return explicit semantic y-axis ticks, or an empty tuple for non-explicit ticks."""
        spec = self._axis_guide(AxisDimension.Y).tick_spec
        return spec.explicit_values if spec.kind == TickSpecKind.EXPLICIT else ()

    def grid(self, visible: bool = True, *, axis: str = "both") -> None:
        """Set semantic grid visibility for x, y, or both axis guides."""
        dimensions = _grid_dimensions(axis)
        for dimension in dimensions:
            self._set_axis_guide(dimension, grid_visible=bool(visible))

    def color_scale(
        self,
        *,
        cmap: str | ColorMapId = ColorMapId.VIRIDIS,
        clim: tuple[float, float],
        id: str | None = None,
        description: str | None = None,
    ) -> ColorScale:
        """Create or register a semantic scalar color scale."""
        colormap_id = _colormap_id(cmap)
        scale = ColorScale(
            id=id or _scale_id(colormap_id.value),
            colormap=ColorMapRef(id=colormap_id),
            normalize=LinearNormalize(vmin=float(clim[0]), vmax=float(clim[1])),
            description=description,
        )
        self._register_color_scale(scale)
        return scale

    def colorbar(
        self,
        color_scale: str | ColorScale,
        *,
        label: str = "",
        orientation: str | ColorbarOrientation = ColorbarOrientation.VERTICAL,
        placement: str | ColorbarPlacement | None = None,
        ticks: npt.ArrayLike | None = None,
        tick_labels: tuple[str, ...] | list[str] | None = None,
        linked_visual_ids: tuple[str, ...] | list[str] = (),
        style: ColorbarGuideStyle | None = None,
        ramp_width_px: float | None = None,
        tick_length_px: float | None = None,
        label_gap_px: float | None = None,
        min_length_px: float | None = None,
        length_fraction: float | None = None,
        id: str | None = None,
    ) -> ColorbarGuide:
        """Create semantic colorbar guide intent for a color scale."""
        guide = ColorbarGuide(
            id=id or f"guide:colorbar-{self._index}-{len(self.colorbar_guides) + 1}",
            panel_id=self.panel.id,
            color_scale_id=self._color_scale_id(color_scale),
            linked_visual_ids=tuple(linked_visual_ids),
            orientation=_colorbar_orientation(orientation),
            placement=_colorbar_placement(placement),
            label=label,
            ticks=_tick_values(ticks) if ticks is not None else (),
            tick_labels=tuple(tick_labels) if tick_labels is not None else None,
            style=_colorbar_style(
                style,
                ramp_width_px=ramp_width_px,
                tick_length_px=tick_length_px,
                label_gap_px=label_gap_px,
                min_length_px=min_length_px,
                length_fraction=length_fraction,
            ),
        )
        self.colorbar_guides.append(guide)
        return guide

    def scatter(
        self,
        x: npt.ArrayLike,
        y: npt.ArrayLike | None = None,
        *,
        c: npt.ArrayLike | None = None,
        color: npt.ArrayLike | None = None,
        color_scale: str | ColorScale | None = None,
        cmap: str | ColorMapId | None = None,
        clim: tuple[float, float] | None = None,
        alpha: float = 1.0,
        s: npt.ArrayLike | float = 36.0,
        size: npt.ArrayLike | float | None = None,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        id: str | None = None,
    ) -> PointVisual:
        """Create a protocol point visual from x/y or an ``(N, 2|3)`` array."""
        positions = _positions(x, y)
        color_value = c if c is not None else color
        encoding = self._scalar_encoding(
            color_value,
            positions.shape[0],
            slot=ScalarColorSlot.COLOR,
            domain=ScalarColorDomain.ITEM,
            color_scale=color_scale,
            cmap=cmap,
            clim=clim,
            alpha=alpha,
        )
        colors = (
            None if encoding is not None else _colors(color_value, positions.shape[0])
        )
        sizes = _sizes(size if size is not None else s, positions.shape[0])
        visual = PointVisual(
            id=id or _visual_id("points"),
            positions=positions,
            colors=colors,
            sizes=sizes,
            coordinate_space=CoordinateSpace.DATA,
            color_encoding=encoding,
            transform=_visual_transform(transform),
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def markers(
        self,
        x: npt.ArrayLike,
        y: npt.ArrayLike | None = None,
        *,
        shape: str
        | MarkerShape
        | tuple[str | MarkerShape, ...]
        | list[str | MarkerShape] = MarkerShape.DISC,
        fill_color: npt.ArrayLike | None = None,
        color: npt.ArrayLike | None = None,
        color_scale: str | ColorScale | None = None,
        cmap: str | ColorMapId | None = None,
        clim: tuple[float, float] | None = None,
        alpha: float = 1.0,
        s: npt.ArrayLike | float = 36.0,
        size: npt.ArrayLike | float | None = None,
        angle: npt.ArrayLike | float = 0.0,
        stroke_color: npt.ArrayLike | None = None,
        stroke_width: float = 0.0,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        id: str | None = None,
    ) -> MarkerVisual:
        """Create a protocol marker visual from x/y or an ``(N, 2|3)`` array."""
        positions = _positions(x, y)
        color_value = fill_color if fill_color is not None else color
        encoding = self._scalar_encoding(
            color_value,
            positions.shape[0],
            slot=ScalarColorSlot.FILL,
            domain=ScalarColorDomain.ITEM,
            color_scale=color_scale,
            cmap=cmap,
            clim=clim,
            alpha=alpha,
        )
        fill_colors = (
            None if encoding is not None else _colors(color_value, positions.shape[0])
        )
        sizes = _sizes(size if size is not None else s, positions.shape[0])
        visual = MarkerVisual(
            id=id or _visual_id("markers"),
            positions=positions,
            shape=_marker_shapes(shape, positions.shape[0]),
            fill_colors=fill_colors,
            sizes=sizes,
            angle=_angles(angle, positions.shape[0]),
            stroke_color=_stroke_color(stroke_color),
            stroke_width=float(stroke_width),
            coordinate_space=CoordinateSpace.DATA,
            fill_color_encoding=encoding,
            transform=_visual_transform(transform),
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def segments(
        self,
        start: npt.ArrayLike,
        end: npt.ArrayLike,
        *,
        color: npt.ArrayLike | None = None,
        width: npt.ArrayLike | float = 1.0,
        cap: str | StrokeCap = StrokeCap.BUTT,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        id: str | None = None,
    ) -> SegmentVisual:
        """Create a protocol segment visual from start/end ``(N, 2|3)`` arrays."""
        start_positions = _positions(start, None)
        end_positions = _positions(end, None)
        if end_positions.shape != start_positions.shape:
            raise ValueError("segment start and end positions must have the same shape")
        colors = _colors(color, start_positions.shape[0])
        widths = _sizes(width, start_positions.shape[0])
        visual = SegmentVisual(
            id=id or _visual_id("segments"),
            start_positions=start_positions,
            end_positions=end_positions,
            colors=colors,
            widths=widths,
            cap=_stroke_cap(cap),
            coordinate_space=CoordinateSpace.DATA,
            transform=_visual_transform(transform),
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def path(
        self,
        positions: npt.ArrayLike,
        path_lengths: tuple[int, ...] | list[int] | npt.ArrayLike | None = None,
        *,
        color: npt.ArrayLike | None = None,
        width: npt.ArrayLike | float = 1.0,
        cap: str | StrokeCap = StrokeCap.BUTT,
        join: str | StrokeJoin = StrokeJoin.MITER,
        miter_limit: float = 4.0,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        id: str | None = None,
    ) -> PathVisual:
        """Create a protocol open polyline path from ordered ``(N, 2|3)`` vertices."""
        position_array = _positions(positions, None)
        lengths = _path_lengths(path_lengths, position_array.shape[0])
        colors = _colors(color, len(lengths))
        widths = _sizes(width, len(lengths))
        visual = PathVisual(
            id=id or _visual_id("path"),
            positions=position_array,
            path_lengths=lengths,
            colors=colors,
            widths=widths,
            cap=_stroke_cap(cap),
            join=_stroke_join(join),
            miter_limit=float(miter_limit),
            coordinate_space=CoordinateSpace.DATA,
            transform=_visual_transform(transform),
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def plot(
        self,
        x: npt.ArrayLike,
        y: npt.ArrayLike | None = None,
        **kwargs: Any,
    ) -> PathVisual:
        """Create one open polyline path from x/y or an ``(N, 2|3)`` array."""
        return self.path(_positions(x, y), None, **kwargs)

    def text(
        self,
        x: npt.ArrayLike,
        y: npt.ArrayLike | None,
        texts: str | tuple[str, ...] | list[str],
        *,
        color: npt.ArrayLike | None = None,
        font_size_px: npt.ArrayLike | float = 13.0,
        font_role: str | FontRole = FontRole.DEFAULT,
        anchor_x: str
        | TextAnchorX
        | tuple[str | TextAnchorX, ...]
        | list[str | TextAnchorX] = TextAnchorX.LEFT,
        anchor_y: str
        | TextAnchorY
        | tuple[str | TextAnchorY, ...]
        | list[str | TextAnchorY] = TextAnchorY.BASELINE,
        rotation_rad: npt.ArrayLike | float = 0.0,
        z_order: int = 0,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        id: str | None = None,
    ) -> TextVisual:
        """Create a protocol TextVisual for explicit labels/annotations."""
        positions = _positions(x, y)
        text_values = _text_values(texts, positions.shape[0])
        visual = TextVisual(
            id=id or _visual_id("text"),
            texts=text_values,
            positions=positions,
            coordinate_space=CoordinateSpace.DATA,
            rgba=_text_rgba(color, positions.shape[0]),
            font_size_px=_positive_values(
                font_size_px, positions.shape[0], field_name="font_size_px"
            ),
            font_role=_font_role(font_role),
            anchor_x=_text_anchor_x(anchor_x, positions.shape[0]),
            anchor_y=_text_anchor_y(anchor_y, positions.shape[0]),
            rotation_rad=_angles(rotation_rad, positions.shape[0]),
            z_order=int(z_order),
            transform=_visual_transform(transform),
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def mesh(
        self,
        positions: npt.ArrayLike,
        faces: npt.ArrayLike,
        *,
        color: npt.ArrayLike,
        color_mode: str | MeshColorMode | None = None,
        coordinate_space: str | CoordinateSpace = CoordinateSpace.DATA,
        shading: str | MeshShading = MeshShading.UNLIT_RGBA,
        normal_mode: str | MeshNormalMode | None = None,
        normals: npt.ArrayLike | None = None,
        normal_generation: str | MeshNormalGeneration = MeshNormalGeneration.NONE,
        order: float = 0.0,
        transform: npt.ArrayLike | VisualTransformBinding | None = None,
        texture: npt.ArrayLike | None = None,
        uvs: npt.ArrayLike | None = None,
        id: str | None = None,
    ) -> MeshVisual:
        """Create a protocol MeshVisual for accepted inline triangle meshes."""
        position_array = _positions(positions, None)
        face_array = _faces(faces)
        texture_resource = self._mesh_texture2d_resource(texture, uvs)
        mesh_shading = _mesh_shading(shading)
        mesh_uvs = None if texture_resource is None else _mesh_uvs(uvs, position_array.shape[0])
        if texture_resource is not None and mesh_shading is not MeshShading.UNLIT_RGBA:
            raise ValueError("texture2d_unlit does not accept explicit mesh shading")
        visual = MeshVisual(
            id=id or _visual_id("mesh"),
            positions=position_array,
            faces=face_array,
            coordinate_space=_coordinate_space(coordinate_space),
            color=_mesh_color(color),
            color_mode=_mesh_color_mode(color_mode),
            shading=(
                MeshShading.TEXTURE2D_UNLIT
                if texture_resource is not None
                else mesh_shading
            ),
            normal_mode=_mesh_normal_mode(normal_mode),
            normals=_mesh_normals(normals),
            normal_generation=_mesh_normal_generation(normal_generation),
            texture2d_id=None if texture_resource is None else texture_resource.id,
            uv_mode=MeshUVMode.NONE if texture_resource is None else MeshUVMode.VERTEX,
            uvs=mesh_uvs,
            order=float(order),
            transform=_visual_transform(transform),
        )
        if texture_resource is not None:
            self.figure.texture2d_resources.append(texture_resource)
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def _mesh_texture2d_resource(
        self, texture: npt.ArrayLike | None, uvs: npt.ArrayLike | None
    ) -> Texture2D | None:
        if texture is None and uvs is None:
            return None
        if texture is None or uvs is None:
            raise ValueError("texture and uvs must be supplied together")
        image = np.asarray(texture)
        if image.dtype != np.dtype(np.uint8):
            raise TypeError("texture2d_invalid_resource: texture must have dtype uint8")
        return Texture2D(id=_texture_id("mesh"), image=image)

    @property
    def _index(self) -> int:
        return int(self.panel.id.rsplit(":", maxsplit=1)[1])

    def _axis_guide(self, dimension: AxisDimension) -> AxisGuide:
        for guide in self.axis_guides:
            if guide.dimension == dimension:
                return guide
        raise LookupError(f"missing {dimension.value} axis guide")

    def _set_axis_guide(self, dimension: AxisDimension, **changes: Any) -> None:
        for index, guide in enumerate(self.axis_guides):
            if guide.dimension == dimension:
                self.axis_guides[index] = replace(guide, **changes)
                return
        raise LookupError(f"missing {dimension.value} axis guide")

    def imshow(
        self,
        image: npt.ArrayLike,
        *,
        extent: tuple[float, float, float, float] | None = None,
        origin: str | ImageOrigin = ImageOrigin.UPPER,
        interpolation: str | ImageInterpolation = ImageInterpolation.NEAREST,
        colormap: str | ImageColormap | ColorMapId | None = None,
        cmap: str | ColorMapId | None = None,
        clim: tuple[float, float] | None = None,
        color_scale: str | ColorScale | None = None,
        id: str | None = None,
    ) -> ImageVisual:
        """Create a protocol image visual."""
        image_array = np.asarray(image)
        if image_array.dtype == np.dtype(np.float64):
            image_array = image_array.astype(np.float32)
        if extent is None:
            height, width = image_array.shape[:2]
            if _origin(origin) == ImageOrigin.UPPER:
                extent = (-0.5, width - 0.5, height - 0.5, -0.5)
            else:
                extent = (-0.5, width - 0.5, -0.5, height - 0.5)
        color_scale_id = self._image_color_scale_id(
            image_array,
            colormap=colormap,
            cmap=cmap,
            clim=clim,
            color_scale=color_scale,
        )
        visual = ImageVisual(
            id=id or _visual_id("image"),
            image=image_array,
            extent=extent,
            coordinate_space=CoordinateSpace.DATA,
            origin=_origin(origin),
            interpolation=_interpolation(interpolation),
            colormap=None if color_scale_id is not None else _colormap(colormap),
            clim=None if color_scale_id is not None else clim,
            color_scale_id=color_scale_id,
        )
        self.visuals.append(visual)
        self.attachments.append(
            VisualAttachment(
                visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
            )
        )
        return visual

    def _register_color_scale(self, scale: ColorScale) -> None:
        for existing in self.figure.color_scale_resources:
            if existing.id == scale.id:
                if existing == scale:
                    return
                raise ValueError(f"color scale id already exists: {scale.id}")
        self.figure.color_scale_resources.append(scale)

    def _color_scale_id(self, color_scale: str | ColorScale) -> str:
        if isinstance(color_scale, ColorScale):
            self._register_color_scale(color_scale)
            return color_scale.id
        for existing in self.figure.color_scale_resources:
            if existing.id == color_scale:
                return color_scale
        raise ValueError(f"unknown color scale id: {color_scale}")

    def _scalar_encoding(
        self,
        values: npt.ArrayLike | None,
        count_: int,
        *,
        slot: ScalarColorSlot,
        domain: ScalarColorDomain,
        color_scale: str | ColorScale | None,
        cmap: str | ColorMapId | None,
        clim: tuple[float, float] | None,
        alpha: float,
    ) -> ScalarColorEncoding | None:
        if color_scale is None and cmap is None:
            return None
        if values is None:
            raise ValueError("scalar color encoding requires scalar values")
        scale_id = self._scalar_color_scale_id(color_scale, cmap=cmap, clim=clim)
        return ScalarColorEncoding(
            slot=slot,
            values=_scalar_values(values, shape=(count_,)),
            color_scale_id=scale_id,
            alpha=float(alpha),
            domain=domain,
        )

    def _scalar_color_scale_id(
        self,
        color_scale: str | ColorScale | None,
        *,
        cmap: str | ColorMapId | None,
        clim: tuple[float, float] | None,
    ) -> str:
        if color_scale is not None:
            if cmap is not None or clim is not None:
                raise ValueError("color_scale is mutually exclusive with cmap/clim")
            return self._color_scale_id(color_scale)
        if cmap is None or clim is None:
            raise ValueError("cmap and clim are required for scalar color encoding")
        scale = self.color_scale(cmap=cmap, clim=clim)
        return scale.id

    def _image_color_scale_id(
        self,
        image: np.ndarray,
        *,
        colormap: str | ImageColormap | ColorMapId | None,
        cmap: str | ColorMapId | None,
        clim: tuple[float, float] | None,
        color_scale: str | ColorScale | None,
    ) -> str | None:
        if image.ndim != 2:
            if color_scale is not None or cmap is not None:
                raise ValueError("color_scale and cmap apply to scalar images only")
            return None
        if color_scale is not None:
            if cmap is not None or _is_s026_colormap(colormap):
                raise ValueError("color_scale is mutually exclusive with cmap")
            return self._color_scale_id(color_scale)
        resolved_cmap = cmap
        if resolved_cmap is None and _is_s026_colormap(colormap):
            resolved_cmap = cast(str | ColorMapId, colormap)
        if resolved_cmap is None:
            return None
        if clim is None:
            raise ValueError("clim is required when using a scalar color scale")
        scale = self.color_scale(cmap=resolved_cmap, clim=clim)
        return scale.id

set_xlim(left: float, right: float) -> tuple[float, float]

Set the semantic x range for this 2D view.

Source code in src/vispy2/protocol.py
267
268
269
270
271
272
273
274
275
276
def set_xlim(self, left: float, right: float) -> tuple[float, float]:
    """Set the semantic x range for this 2D view."""
    self.view = View2D(
        id=self.view.id,
        panel_id=self.view.panel_id,
        x_range=(float(left), float(right)),
        y_range=self.view.y_range,
        aspect_policy=self.view.aspect_policy,
    )
    return self.view.x_range

set_ylim(bottom: float, top: float) -> tuple[float, float]

Set the semantic y range for this 2D view.

Source code in src/vispy2/protocol.py
278
279
280
281
282
283
284
285
286
287
def set_ylim(self, bottom: float, top: float) -> tuple[float, float]:
    """Set the semantic y range for this 2D view."""
    self.view = View2D(
        id=self.view.id,
        panel_id=self.view.panel_id,
        x_range=self.view.x_range,
        y_range=(float(bottom), float(top)),
        aspect_policy=self.view.aspect_policy,
    )
    return self.view.y_range

set_view2d(*, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, clip: bool | None = None) -> View2D

Set deterministic S027 View2D state.

Source code in src/vispy2/protocol.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def set_view2d(
    self,
    *,
    xlim: tuple[float, float] | None = None,
    ylim: tuple[float, float] | None = None,
    clip: bool | None = None,
) -> View2D:
    """Set deterministic S027 View2D state."""
    next_xlim = self.view.xlim if xlim is None else (float(xlim[0]), float(xlim[1]))
    next_ylim = self.view.ylim if ylim is None else (float(ylim[0]), float(ylim[1]))
    self.view = View2D(
        id=self.view.id,
        panel_id=self.view.panel_id,
        x_range=next_xlim,
        y_range=next_ylim,
        aspect_policy=self.view.aspect_policy,
        kind=self.view.kind,
        clip=self.view.clip if clip is None else bool(clip),
    )
    return self.view

get_xlim() -> tuple[float, float]

Return the semantic x range for this 2D view.

Source code in src/vispy2/protocol.py
310
311
312
def get_xlim(self) -> tuple[float, float]:
    """Return the semantic x range for this 2D view."""
    return self.view.x_range

get_ylim() -> tuple[float, float]

Return the semantic y range for this 2D view.

Source code in src/vispy2/protocol.py
314
315
316
def get_ylim(self) -> tuple[float, float]:
    """Return the semantic y range for this 2D view."""
    return self.view.y_range

set_xlabel(text: str | None) -> str | None

Set the semantic x-axis label.

Source code in src/vispy2/protocol.py
318
319
320
321
def set_xlabel(self, text: str | None) -> str | None:
    """Set the semantic x-axis label."""
    self._set_axis_guide(AxisDimension.X, label_text=text)
    return text

get_xlabel() -> str | None

Return the semantic x-axis label.

Source code in src/vispy2/protocol.py
323
324
325
def get_xlabel(self) -> str | None:
    """Return the semantic x-axis label."""
    return self._axis_guide(AxisDimension.X).label_text

set_ylabel(text: str | None) -> str | None

Set the semantic y-axis label.

Source code in src/vispy2/protocol.py
327
328
329
330
def set_ylabel(self, text: str | None) -> str | None:
    """Set the semantic y-axis label."""
    self._set_axis_guide(AxisDimension.Y, label_text=text)
    return text

get_ylabel() -> str | None

Return the semantic y-axis label.

Source code in src/vispy2/protocol.py
332
333
334
def get_ylabel(self) -> str | None:
    """Return the semantic y-axis label."""
    return self._axis_guide(AxisDimension.Y).label_text

set_title(text: str | None) -> str | None

Set or clear the semantic panel title.

Source code in src/vispy2/protocol.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def set_title(self, text: str | None) -> str | None:
    """Set or clear the semantic panel title."""
    self.panel_text_guides = [
        guide
        for guide in self.panel_text_guides
        if guide.role != PanelTextRole.TITLE
    ]
    if text:
        self.panel_text_guides.append(
            PanelTextGuide(
                id=f"guide:title-{self._index}",
                panel_id=self.panel.id,
                role=PanelTextRole.TITLE,
                text=text,
            )
        )
    return text

get_title() -> str | None

Return the semantic panel title, if any.

Source code in src/vispy2/protocol.py
354
355
356
357
358
359
def get_title(self) -> str | None:
    """Return the semantic panel title, if any."""
    for guide in self.panel_text_guides:
        if guide.role == PanelTextRole.TITLE:
            return guide.text
    return None

set_xticks(ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None) -> tuple[float, ...]

Set explicit semantic x-axis tick values and optional labels.

Source code in src/vispy2/protocol.py
361
362
363
364
365
366
367
368
369
def set_xticks(
    self, ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None
) -> tuple[float, ...]:
    """Set explicit semantic x-axis tick values and optional labels."""
    values = _tick_values(ticks)
    self._set_axis_guide(
        AxisDimension.X, tick_spec=_explicit_tick_spec(values, labels)
    )
    return values

get_xticks() -> tuple[float, ...]

Return explicit semantic x-axis ticks, or an empty tuple for non-explicit ticks.

Source code in src/vispy2/protocol.py
371
372
373
374
def get_xticks(self) -> tuple[float, ...]:
    """Return explicit semantic x-axis ticks, or an empty tuple for non-explicit ticks."""
    spec = self._axis_guide(AxisDimension.X).tick_spec
    return spec.explicit_values if spec.kind == TickSpecKind.EXPLICIT else ()

set_yticks(ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None) -> tuple[float, ...]

Set explicit semantic y-axis tick values and optional labels.

Source code in src/vispy2/protocol.py
376
377
378
379
380
381
382
383
384
def set_yticks(
    self, ticks: npt.ArrayLike, labels: tuple[str, ...] | list[str] | None = None
) -> tuple[float, ...]:
    """Set explicit semantic y-axis tick values and optional labels."""
    values = _tick_values(ticks)
    self._set_axis_guide(
        AxisDimension.Y, tick_spec=_explicit_tick_spec(values, labels)
    )
    return values

get_yticks() -> tuple[float, ...]

Return explicit semantic y-axis ticks, or an empty tuple for non-explicit ticks.

Source code in src/vispy2/protocol.py
386
387
388
389
def get_yticks(self) -> tuple[float, ...]:
    """Return explicit semantic y-axis ticks, or an empty tuple for non-explicit ticks."""
    spec = self._axis_guide(AxisDimension.Y).tick_spec
    return spec.explicit_values if spec.kind == TickSpecKind.EXPLICIT else ()

grid(visible: bool = True, *, axis: str = 'both') -> None

Set semantic grid visibility for x, y, or both axis guides.

Source code in src/vispy2/protocol.py
391
392
393
394
395
def grid(self, visible: bool = True, *, axis: str = "both") -> None:
    """Set semantic grid visibility for x, y, or both axis guides."""
    dimensions = _grid_dimensions(axis)
    for dimension in dimensions:
        self._set_axis_guide(dimension, grid_visible=bool(visible))

color_scale(*, cmap: str | ColorMapId = ColorMapId.VIRIDIS, clim: tuple[float, float], id: str | None = None, description: str | None = None) -> ColorScale

Create or register a semantic scalar color scale.

Source code in src/vispy2/protocol.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def color_scale(
    self,
    *,
    cmap: str | ColorMapId = ColorMapId.VIRIDIS,
    clim: tuple[float, float],
    id: str | None = None,
    description: str | None = None,
) -> ColorScale:
    """Create or register a semantic scalar color scale."""
    colormap_id = _colormap_id(cmap)
    scale = ColorScale(
        id=id or _scale_id(colormap_id.value),
        colormap=ColorMapRef(id=colormap_id),
        normalize=LinearNormalize(vmin=float(clim[0]), vmax=float(clim[1])),
        description=description,
    )
    self._register_color_scale(scale)
    return scale

colorbar(color_scale: str | ColorScale, *, label: str = '', orientation: str | ColorbarOrientation = ColorbarOrientation.VERTICAL, placement: str | ColorbarPlacement | None = None, ticks: npt.ArrayLike | None = None, tick_labels: tuple[str, ...] | list[str] | None = None, linked_visual_ids: tuple[str, ...] | list[str] = (), style: ColorbarGuideStyle | None = None, ramp_width_px: float | None = None, tick_length_px: float | None = None, label_gap_px: float | None = None, min_length_px: float | None = None, length_fraction: float | None = None, id: str | None = None) -> ColorbarGuide

Create semantic colorbar guide intent for a color scale.

Source code in src/vispy2/protocol.py
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
def colorbar(
    self,
    color_scale: str | ColorScale,
    *,
    label: str = "",
    orientation: str | ColorbarOrientation = ColorbarOrientation.VERTICAL,
    placement: str | ColorbarPlacement | None = None,
    ticks: npt.ArrayLike | None = None,
    tick_labels: tuple[str, ...] | list[str] | None = None,
    linked_visual_ids: tuple[str, ...] | list[str] = (),
    style: ColorbarGuideStyle | None = None,
    ramp_width_px: float | None = None,
    tick_length_px: float | None = None,
    label_gap_px: float | None = None,
    min_length_px: float | None = None,
    length_fraction: float | None = None,
    id: str | None = None,
) -> ColorbarGuide:
    """Create semantic colorbar guide intent for a color scale."""
    guide = ColorbarGuide(
        id=id or f"guide:colorbar-{self._index}-{len(self.colorbar_guides) + 1}",
        panel_id=self.panel.id,
        color_scale_id=self._color_scale_id(color_scale),
        linked_visual_ids=tuple(linked_visual_ids),
        orientation=_colorbar_orientation(orientation),
        placement=_colorbar_placement(placement),
        label=label,
        ticks=_tick_values(ticks) if ticks is not None else (),
        tick_labels=tuple(tick_labels) if tick_labels is not None else None,
        style=_colorbar_style(
            style,
            ramp_width_px=ramp_width_px,
            tick_length_px=tick_length_px,
            label_gap_px=label_gap_px,
            min_length_px=min_length_px,
            length_fraction=length_fraction,
        ),
    )
    self.colorbar_guides.append(guide)
    return guide

scatter(x: npt.ArrayLike, y: npt.ArrayLike | None = None, *, c: npt.ArrayLike | None = None, color: npt.ArrayLike | None = None, color_scale: str | ColorScale | None = None, cmap: str | ColorMapId | None = None, clim: tuple[float, float] | None = None, alpha: float = 1.0, s: npt.ArrayLike | float = 36.0, size: npt.ArrayLike | float | None = None, transform: npt.ArrayLike | VisualTransformBinding | None = None, id: str | None = None) -> PointVisual

Create a protocol point visual from x/y or an (N, 2|3) array.

Source code in src/vispy2/protocol.py
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
def scatter(
    self,
    x: npt.ArrayLike,
    y: npt.ArrayLike | None = None,
    *,
    c: npt.ArrayLike | None = None,
    color: npt.ArrayLike | None = None,
    color_scale: str | ColorScale | None = None,
    cmap: str | ColorMapId | None = None,
    clim: tuple[float, float] | None = None,
    alpha: float = 1.0,
    s: npt.ArrayLike | float = 36.0,
    size: npt.ArrayLike | float | None = None,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    id: str | None = None,
) -> PointVisual:
    """Create a protocol point visual from x/y or an ``(N, 2|3)`` array."""
    positions = _positions(x, y)
    color_value = c if c is not None else color
    encoding = self._scalar_encoding(
        color_value,
        positions.shape[0],
        slot=ScalarColorSlot.COLOR,
        domain=ScalarColorDomain.ITEM,
        color_scale=color_scale,
        cmap=cmap,
        clim=clim,
        alpha=alpha,
    )
    colors = (
        None if encoding is not None else _colors(color_value, positions.shape[0])
    )
    sizes = _sizes(size if size is not None else s, positions.shape[0])
    visual = PointVisual(
        id=id or _visual_id("points"),
        positions=positions,
        colors=colors,
        sizes=sizes,
        coordinate_space=CoordinateSpace.DATA,
        color_encoding=encoding,
        transform=_visual_transform(transform),
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

markers(x: npt.ArrayLike, y: npt.ArrayLike | None = None, *, shape: str | MarkerShape | tuple[str | MarkerShape, ...] | list[str | MarkerShape] = MarkerShape.DISC, fill_color: npt.ArrayLike | None = None, color: npt.ArrayLike | None = None, color_scale: str | ColorScale | None = None, cmap: str | ColorMapId | None = None, clim: tuple[float, float] | None = None, alpha: float = 1.0, s: npt.ArrayLike | float = 36.0, size: npt.ArrayLike | float | None = None, angle: npt.ArrayLike | float = 0.0, stroke_color: npt.ArrayLike | None = None, stroke_width: float = 0.0, transform: npt.ArrayLike | VisualTransformBinding | None = None, id: str | None = None) -> MarkerVisual

Create a protocol marker visual from x/y or an (N, 2|3) array.

Source code in src/vispy2/protocol.py
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
def markers(
    self,
    x: npt.ArrayLike,
    y: npt.ArrayLike | None = None,
    *,
    shape: str
    | MarkerShape
    | tuple[str | MarkerShape, ...]
    | list[str | MarkerShape] = MarkerShape.DISC,
    fill_color: npt.ArrayLike | None = None,
    color: npt.ArrayLike | None = None,
    color_scale: str | ColorScale | None = None,
    cmap: str | ColorMapId | None = None,
    clim: tuple[float, float] | None = None,
    alpha: float = 1.0,
    s: npt.ArrayLike | float = 36.0,
    size: npt.ArrayLike | float | None = None,
    angle: npt.ArrayLike | float = 0.0,
    stroke_color: npt.ArrayLike | None = None,
    stroke_width: float = 0.0,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    id: str | None = None,
) -> MarkerVisual:
    """Create a protocol marker visual from x/y or an ``(N, 2|3)`` array."""
    positions = _positions(x, y)
    color_value = fill_color if fill_color is not None else color
    encoding = self._scalar_encoding(
        color_value,
        positions.shape[0],
        slot=ScalarColorSlot.FILL,
        domain=ScalarColorDomain.ITEM,
        color_scale=color_scale,
        cmap=cmap,
        clim=clim,
        alpha=alpha,
    )
    fill_colors = (
        None if encoding is not None else _colors(color_value, positions.shape[0])
    )
    sizes = _sizes(size if size is not None else s, positions.shape[0])
    visual = MarkerVisual(
        id=id or _visual_id("markers"),
        positions=positions,
        shape=_marker_shapes(shape, positions.shape[0]),
        fill_colors=fill_colors,
        sizes=sizes,
        angle=_angles(angle, positions.shape[0]),
        stroke_color=_stroke_color(stroke_color),
        stroke_width=float(stroke_width),
        coordinate_space=CoordinateSpace.DATA,
        fill_color_encoding=encoding,
        transform=_visual_transform(transform),
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

segments(start: npt.ArrayLike, end: npt.ArrayLike, *, color: npt.ArrayLike | None = None, width: npt.ArrayLike | float = 1.0, cap: str | StrokeCap = StrokeCap.BUTT, transform: npt.ArrayLike | VisualTransformBinding | None = None, id: str | None = None) -> SegmentVisual

Create a protocol segment visual from start/end (N, 2|3) arrays.

Source code in src/vispy2/protocol.py
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
def segments(
    self,
    start: npt.ArrayLike,
    end: npt.ArrayLike,
    *,
    color: npt.ArrayLike | None = None,
    width: npt.ArrayLike | float = 1.0,
    cap: str | StrokeCap = StrokeCap.BUTT,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    id: str | None = None,
) -> SegmentVisual:
    """Create a protocol segment visual from start/end ``(N, 2|3)`` arrays."""
    start_positions = _positions(start, None)
    end_positions = _positions(end, None)
    if end_positions.shape != start_positions.shape:
        raise ValueError("segment start and end positions must have the same shape")
    colors = _colors(color, start_positions.shape[0])
    widths = _sizes(width, start_positions.shape[0])
    visual = SegmentVisual(
        id=id or _visual_id("segments"),
        start_positions=start_positions,
        end_positions=end_positions,
        colors=colors,
        widths=widths,
        cap=_stroke_cap(cap),
        coordinate_space=CoordinateSpace.DATA,
        transform=_visual_transform(transform),
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

path(positions: npt.ArrayLike, path_lengths: tuple[int, ...] | list[int] | npt.ArrayLike | None = None, *, color: npt.ArrayLike | None = None, width: npt.ArrayLike | float = 1.0, cap: str | StrokeCap = StrokeCap.BUTT, join: str | StrokeJoin = StrokeJoin.MITER, miter_limit: float = 4.0, transform: npt.ArrayLike | VisualTransformBinding | None = None, id: str | None = None) -> PathVisual

Create a protocol open polyline path from ordered (N, 2|3) vertices.

Source code in src/vispy2/protocol.py
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
def path(
    self,
    positions: npt.ArrayLike,
    path_lengths: tuple[int, ...] | list[int] | npt.ArrayLike | None = None,
    *,
    color: npt.ArrayLike | None = None,
    width: npt.ArrayLike | float = 1.0,
    cap: str | StrokeCap = StrokeCap.BUTT,
    join: str | StrokeJoin = StrokeJoin.MITER,
    miter_limit: float = 4.0,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    id: str | None = None,
) -> PathVisual:
    """Create a protocol open polyline path from ordered ``(N, 2|3)`` vertices."""
    position_array = _positions(positions, None)
    lengths = _path_lengths(path_lengths, position_array.shape[0])
    colors = _colors(color, len(lengths))
    widths = _sizes(width, len(lengths))
    visual = PathVisual(
        id=id or _visual_id("path"),
        positions=position_array,
        path_lengths=lengths,
        colors=colors,
        widths=widths,
        cap=_stroke_cap(cap),
        join=_stroke_join(join),
        miter_limit=float(miter_limit),
        coordinate_space=CoordinateSpace.DATA,
        transform=_visual_transform(transform),
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

plot(x: npt.ArrayLike, y: npt.ArrayLike | None = None, **kwargs: Any) -> PathVisual

Create one open polyline path from x/y or an (N, 2|3) array.

Source code in src/vispy2/protocol.py
642
643
644
645
646
647
648
649
def plot(
    self,
    x: npt.ArrayLike,
    y: npt.ArrayLike | None = None,
    **kwargs: Any,
) -> PathVisual:
    """Create one open polyline path from x/y or an ``(N, 2|3)`` array."""
    return self.path(_positions(x, y), None, **kwargs)

text(x: npt.ArrayLike, y: npt.ArrayLike | None, texts: str | tuple[str, ...] | list[str], *, color: npt.ArrayLike | None = None, font_size_px: npt.ArrayLike | float = 13.0, font_role: str | FontRole = FontRole.DEFAULT, anchor_x: str | TextAnchorX | tuple[str | TextAnchorX, ...] | list[str | TextAnchorX] = TextAnchorX.LEFT, anchor_y: str | TextAnchorY | tuple[str | TextAnchorY, ...] | list[str | TextAnchorY] = TextAnchorY.BASELINE, rotation_rad: npt.ArrayLike | float = 0.0, z_order: int = 0, transform: npt.ArrayLike | VisualTransformBinding | None = None, id: str | None = None) -> TextVisual

Create a protocol TextVisual for explicit labels/annotations.

Source code in src/vispy2/protocol.py
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
def text(
    self,
    x: npt.ArrayLike,
    y: npt.ArrayLike | None,
    texts: str | tuple[str, ...] | list[str],
    *,
    color: npt.ArrayLike | None = None,
    font_size_px: npt.ArrayLike | float = 13.0,
    font_role: str | FontRole = FontRole.DEFAULT,
    anchor_x: str
    | TextAnchorX
    | tuple[str | TextAnchorX, ...]
    | list[str | TextAnchorX] = TextAnchorX.LEFT,
    anchor_y: str
    | TextAnchorY
    | tuple[str | TextAnchorY, ...]
    | list[str | TextAnchorY] = TextAnchorY.BASELINE,
    rotation_rad: npt.ArrayLike | float = 0.0,
    z_order: int = 0,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    id: str | None = None,
) -> TextVisual:
    """Create a protocol TextVisual for explicit labels/annotations."""
    positions = _positions(x, y)
    text_values = _text_values(texts, positions.shape[0])
    visual = TextVisual(
        id=id or _visual_id("text"),
        texts=text_values,
        positions=positions,
        coordinate_space=CoordinateSpace.DATA,
        rgba=_text_rgba(color, positions.shape[0]),
        font_size_px=_positive_values(
            font_size_px, positions.shape[0], field_name="font_size_px"
        ),
        font_role=_font_role(font_role),
        anchor_x=_text_anchor_x(anchor_x, positions.shape[0]),
        anchor_y=_text_anchor_y(anchor_y, positions.shape[0]),
        rotation_rad=_angles(rotation_rad, positions.shape[0]),
        z_order=int(z_order),
        transform=_visual_transform(transform),
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

mesh(positions: npt.ArrayLike, faces: npt.ArrayLike, *, color: npt.ArrayLike, color_mode: str | MeshColorMode | None = None, coordinate_space: str | CoordinateSpace = CoordinateSpace.DATA, shading: str | MeshShading = MeshShading.UNLIT_RGBA, normal_mode: str | MeshNormalMode | None = None, normals: npt.ArrayLike | None = None, normal_generation: str | MeshNormalGeneration = MeshNormalGeneration.NONE, order: float = 0.0, transform: npt.ArrayLike | VisualTransformBinding | None = None, texture: npt.ArrayLike | None = None, uvs: npt.ArrayLike | None = None, id: str | None = None) -> MeshVisual

Create a protocol MeshVisual for accepted inline triangle meshes.

Source code in src/vispy2/protocol.py
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def mesh(
    self,
    positions: npt.ArrayLike,
    faces: npt.ArrayLike,
    *,
    color: npt.ArrayLike,
    color_mode: str | MeshColorMode | None = None,
    coordinate_space: str | CoordinateSpace = CoordinateSpace.DATA,
    shading: str | MeshShading = MeshShading.UNLIT_RGBA,
    normal_mode: str | MeshNormalMode | None = None,
    normals: npt.ArrayLike | None = None,
    normal_generation: str | MeshNormalGeneration = MeshNormalGeneration.NONE,
    order: float = 0.0,
    transform: npt.ArrayLike | VisualTransformBinding | None = None,
    texture: npt.ArrayLike | None = None,
    uvs: npt.ArrayLike | None = None,
    id: str | None = None,
) -> MeshVisual:
    """Create a protocol MeshVisual for accepted inline triangle meshes."""
    position_array = _positions(positions, None)
    face_array = _faces(faces)
    texture_resource = self._mesh_texture2d_resource(texture, uvs)
    mesh_shading = _mesh_shading(shading)
    mesh_uvs = None if texture_resource is None else _mesh_uvs(uvs, position_array.shape[0])
    if texture_resource is not None and mesh_shading is not MeshShading.UNLIT_RGBA:
        raise ValueError("texture2d_unlit does not accept explicit mesh shading")
    visual = MeshVisual(
        id=id or _visual_id("mesh"),
        positions=position_array,
        faces=face_array,
        coordinate_space=_coordinate_space(coordinate_space),
        color=_mesh_color(color),
        color_mode=_mesh_color_mode(color_mode),
        shading=(
            MeshShading.TEXTURE2D_UNLIT
            if texture_resource is not None
            else mesh_shading
        ),
        normal_mode=_mesh_normal_mode(normal_mode),
        normals=_mesh_normals(normals),
        normal_generation=_mesh_normal_generation(normal_generation),
        texture2d_id=None if texture_resource is None else texture_resource.id,
        uv_mode=MeshUVMode.NONE if texture_resource is None else MeshUVMode.VERTEX,
        uvs=mesh_uvs,
        order=float(order),
        transform=_visual_transform(transform),
    )
    if texture_resource is not None:
        self.figure.texture2d_resources.append(texture_resource)
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

imshow(image: npt.ArrayLike, *, extent: tuple[float, float, float, float] | None = None, origin: str | ImageOrigin = ImageOrigin.UPPER, interpolation: str | ImageInterpolation = ImageInterpolation.NEAREST, colormap: str | ImageColormap | ColorMapId | None = None, cmap: str | ColorMapId | None = None, clim: tuple[float, float] | None = None, color_scale: str | ColorScale | None = None, id: str | None = None) -> ImageVisual

Create a protocol image visual.

Source code in src/vispy2/protocol.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
def imshow(
    self,
    image: npt.ArrayLike,
    *,
    extent: tuple[float, float, float, float] | None = None,
    origin: str | ImageOrigin = ImageOrigin.UPPER,
    interpolation: str | ImageInterpolation = ImageInterpolation.NEAREST,
    colormap: str | ImageColormap | ColorMapId | None = None,
    cmap: str | ColorMapId | None = None,
    clim: tuple[float, float] | None = None,
    color_scale: str | ColorScale | None = None,
    id: str | None = None,
) -> ImageVisual:
    """Create a protocol image visual."""
    image_array = np.asarray(image)
    if image_array.dtype == np.dtype(np.float64):
        image_array = image_array.astype(np.float32)
    if extent is None:
        height, width = image_array.shape[:2]
        if _origin(origin) == ImageOrigin.UPPER:
            extent = (-0.5, width - 0.5, height - 0.5, -0.5)
        else:
            extent = (-0.5, width - 0.5, -0.5, height - 0.5)
    color_scale_id = self._image_color_scale_id(
        image_array,
        colormap=colormap,
        cmap=cmap,
        clim=clim,
        color_scale=color_scale,
    )
    visual = ImageVisual(
        id=id or _visual_id("image"),
        image=image_array,
        extent=extent,
        coordinate_space=CoordinateSpace.DATA,
        origin=_origin(origin),
        interpolation=_interpolation(interpolation),
        colormap=None if color_scale_id is not None else _colormap(colormap),
        clim=None if color_scale_id is not None else clim,
        color_scale_id=color_scale_id,
    )
    self.visuals.append(visual)
    self.attachments.append(
        VisualAttachment(
            visual_id=visual.id, panel_id=self.panel.id, view_id=self.view.id
        )
    )
    return visual

Figure dataclass

Container for the minimal VisPy2 protocol scene.

Source code in src/vispy2/protocol.py
 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
@dataclass(slots=True)
class Figure:
    """Container for the minimal VisPy2 protocol scene."""

    axes: list["Axes"] = field(default_factory=list)
    id: str = "figure:main"
    color_scale_resources: list[ColorScale] = field(default_factory=list)
    texture2d_resources: list[Texture2D] = field(default_factory=list)

    def add_axes(self) -> "Axes":
        """Add one protocol-producing axes to the figure."""
        axes = Axes(figure=self)
        self.axes.append(axes)
        return axes

    def visuals(
        self,
    ) -> tuple[
        PointVisual
        | MarkerVisual
        | SegmentVisual
        | PathVisual
        | MeshVisual
        | ImageVisual
        | TextVisual,
        ...,
    ]:
        """Return protocol visuals in creation order."""
        return tuple(visual for axes in self.axes for visual in axes.visuals)

    def panels(self) -> tuple[Panel, ...]:
        """Return semantic panels without expanding guide visuals."""
        return tuple(axes.panel for axes in self.axes)

    def views(self) -> tuple[View2D, ...]:
        """Return semantic 2D views without expanding guide visuals."""
        return tuple(axes.view for axes in self.axes)

    def attachments(self) -> tuple[VisualAttachment, ...]:
        """Return data visual attachments to panels/views."""
        return tuple(
            attachment for axes in self.axes for attachment in axes.attachments
        )

    def axis_guides(self) -> tuple[AxisGuide, ...]:
        """Return semantic axis guide intent without expanding guide visuals."""
        return tuple(guide for axes in self.axes for guide in axes.axis_guides)

    def panel_text_guides(self) -> tuple[PanelTextGuide, ...]:
        """Return semantic panel text guide intent without expanding guide visuals."""
        return tuple(guide for axes in self.axes for guide in axes.panel_text_guides)

    def color_scales(self) -> tuple[ColorScale, ...]:
        """Return semantic scalar color scale resources."""
        return tuple(self.color_scale_resources)

    def texture_resources(self) -> tuple[Texture2D, ...]:
        """Return semantic Texture2D resources."""
        return tuple(self.texture2d_resources)

    def colorbar_guides(self) -> tuple[ColorbarGuide, ...]:
        """Return semantic colorbar guide intent."""
        return tuple(guide for axes in self.axes for guide in axes.colorbar_guides)

    def render_matplotlib(self) -> tuple[Any, Any]:
        """Render the protocol scene through the Matplotlib reference backend."""
        import matplotlib.pyplot as plt

        fig, mpl_axes = plt.subplots()
        color_scales = {scale.id: scale for scale in self.color_scale_resources}
        for visual in self.visuals():
            if isinstance(visual, ImageVisual):
                render_image_visual(mpl_axes, visual, color_scales=color_scales)
            elif isinstance(visual, MarkerVisual):
                render_marker_visual(mpl_axes, visual, color_scales=color_scales)
            elif isinstance(visual, SegmentVisual):
                render_segment_visual(mpl_axes, visual)
            elif isinstance(visual, PathVisual):
                render_path_visual(mpl_axes, visual)
            elif isinstance(visual, MeshVisual):
                render_mesh_visual(mpl_axes, visual)
            elif isinstance(visual, PointVisual):
                render_point_visual(mpl_axes, visual, color_scales=color_scales)
            elif isinstance(visual, TextVisual):
                render_text_visual(mpl_axes, visual)
            else:
                raise TypeError(f"unsupported protocol visual: {type(visual)!r}")
        if self.axes:
            axes_model = self.axes[0]
            view = axes_model.view
            mpl_axes.set_xlim(view.x_range)
            mpl_axes.set_ylim(view.y_range)
            mpl_axes.set_aspect(
                "equal" if view.aspect_policy.value == "equal" else "auto"
            )
            render_axis_guides(mpl_axes, view, tuple(axes_model.axis_guides))
            render_panel_text_guides(mpl_axes, tuple(axes_model.panel_text_guides))
            for guide in axes_model.colorbar_guides:
                render_colorbar_guide(mpl_axes, guide, color_scales=color_scales)
        return fig, mpl_axes

    def render_matplotlib_with_layout(
        self, *, snapshot_id: str = "layout:matplotlib"
    ) -> MatplotlibProtocolRenderResult:
        """Render through Matplotlib and return the resolved layout snapshot."""
        axes_model = self.axes[0] if self.axes else None
        return render_protocol_scene_with_layout(
            visuals=self.visuals(),
            snapshot_id=snapshot_id,
            view=axes_model.view if axes_model is not None else None,
            axis_guides=tuple(axes_model.axis_guides) if axes_model is not None else (),
            panel_text_guides=tuple(axes_model.panel_text_guides)
            if axes_model is not None
            else (),
            colorbar_guides=tuple(axes_model.colorbar_guides)
            if axes_model is not None
            else (),
            color_scales={scale.id: scale for scale in self.color_scale_resources},
        )

    def savefig(self, path: str | Path, **kwargs: Any) -> None:
        """Render through Matplotlib and save the result."""
        fig, _ = self.render_matplotlib()
        try:
            fig.savefig(path, **kwargs)
        finally:
            import matplotlib.pyplot as plt

            plt.close(fig)

    def show(self) -> tuple[Any, Any]:
        """Render and show the Matplotlib figure."""
        fig, mpl_axes = self.render_matplotlib()
        import matplotlib.pyplot as plt

        plt.show()
        return fig, mpl_axes

add_axes() -> 'Axes'

Add one protocol-producing axes to the figure.

Source code in src/vispy2/protocol.py
93
94
95
96
97
def add_axes(self) -> "Axes":
    """Add one protocol-producing axes to the figure."""
    axes = Axes(figure=self)
    self.axes.append(axes)
    return axes

visuals() -> tuple[PointVisual | MarkerVisual | SegmentVisual | PathVisual | MeshVisual | ImageVisual | TextVisual, ...]

Return protocol visuals in creation order.

Source code in src/vispy2/protocol.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def visuals(
    self,
) -> tuple[
    PointVisual
    | MarkerVisual
    | SegmentVisual
    | PathVisual
    | MeshVisual
    | ImageVisual
    | TextVisual,
    ...,
]:
    """Return protocol visuals in creation order."""
    return tuple(visual for axes in self.axes for visual in axes.visuals)

panels() -> tuple[Panel, ...]

Return semantic panels without expanding guide visuals.

Source code in src/vispy2/protocol.py
114
115
116
def panels(self) -> tuple[Panel, ...]:
    """Return semantic panels without expanding guide visuals."""
    return tuple(axes.panel for axes in self.axes)

views() -> tuple[View2D, ...]

Return semantic 2D views without expanding guide visuals.

Source code in src/vispy2/protocol.py
118
119
120
def views(self) -> tuple[View2D, ...]:
    """Return semantic 2D views without expanding guide visuals."""
    return tuple(axes.view for axes in self.axes)

attachments() -> tuple[VisualAttachment, ...]

Return data visual attachments to panels/views.

Source code in src/vispy2/protocol.py
122
123
124
125
126
def attachments(self) -> tuple[VisualAttachment, ...]:
    """Return data visual attachments to panels/views."""
    return tuple(
        attachment for axes in self.axes for attachment in axes.attachments
    )

axis_guides() -> tuple[AxisGuide, ...]

Return semantic axis guide intent without expanding guide visuals.

Source code in src/vispy2/protocol.py
128
129
130
def axis_guides(self) -> tuple[AxisGuide, ...]:
    """Return semantic axis guide intent without expanding guide visuals."""
    return tuple(guide for axes in self.axes for guide in axes.axis_guides)

panel_text_guides() -> tuple[PanelTextGuide, ...]

Return semantic panel text guide intent without expanding guide visuals.

Source code in src/vispy2/protocol.py
132
133
134
def panel_text_guides(self) -> tuple[PanelTextGuide, ...]:
    """Return semantic panel text guide intent without expanding guide visuals."""
    return tuple(guide for axes in self.axes for guide in axes.panel_text_guides)

color_scales() -> tuple[ColorScale, ...]

Return semantic scalar color scale resources.

Source code in src/vispy2/protocol.py
136
137
138
def color_scales(self) -> tuple[ColorScale, ...]:
    """Return semantic scalar color scale resources."""
    return tuple(self.color_scale_resources)

texture_resources() -> tuple[Texture2D, ...]

Return semantic Texture2D resources.

Source code in src/vispy2/protocol.py
140
141
142
def texture_resources(self) -> tuple[Texture2D, ...]:
    """Return semantic Texture2D resources."""
    return tuple(self.texture2d_resources)

colorbar_guides() -> tuple[ColorbarGuide, ...]

Return semantic colorbar guide intent.

Source code in src/vispy2/protocol.py
144
145
146
def colorbar_guides(self) -> tuple[ColorbarGuide, ...]:
    """Return semantic colorbar guide intent."""
    return tuple(guide for axes in self.axes for guide in axes.colorbar_guides)

render_matplotlib() -> tuple[Any, Any]

Render the protocol scene through the Matplotlib reference backend.

Source code in src/vispy2/protocol.py
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
def render_matplotlib(self) -> tuple[Any, Any]:
    """Render the protocol scene through the Matplotlib reference backend."""
    import matplotlib.pyplot as plt

    fig, mpl_axes = plt.subplots()
    color_scales = {scale.id: scale for scale in self.color_scale_resources}
    for visual in self.visuals():
        if isinstance(visual, ImageVisual):
            render_image_visual(mpl_axes, visual, color_scales=color_scales)
        elif isinstance(visual, MarkerVisual):
            render_marker_visual(mpl_axes, visual, color_scales=color_scales)
        elif isinstance(visual, SegmentVisual):
            render_segment_visual(mpl_axes, visual)
        elif isinstance(visual, PathVisual):
            render_path_visual(mpl_axes, visual)
        elif isinstance(visual, MeshVisual):
            render_mesh_visual(mpl_axes, visual)
        elif isinstance(visual, PointVisual):
            render_point_visual(mpl_axes, visual, color_scales=color_scales)
        elif isinstance(visual, TextVisual):
            render_text_visual(mpl_axes, visual)
        else:
            raise TypeError(f"unsupported protocol visual: {type(visual)!r}")
    if self.axes:
        axes_model = self.axes[0]
        view = axes_model.view
        mpl_axes.set_xlim(view.x_range)
        mpl_axes.set_ylim(view.y_range)
        mpl_axes.set_aspect(
            "equal" if view.aspect_policy.value == "equal" else "auto"
        )
        render_axis_guides(mpl_axes, view, tuple(axes_model.axis_guides))
        render_panel_text_guides(mpl_axes, tuple(axes_model.panel_text_guides))
        for guide in axes_model.colorbar_guides:
            render_colorbar_guide(mpl_axes, guide, color_scales=color_scales)
    return fig, mpl_axes

render_matplotlib_with_layout(*, snapshot_id: str = 'layout:matplotlib') -> MatplotlibProtocolRenderResult

Render through Matplotlib and return the resolved layout snapshot.

Source code in src/vispy2/protocol.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def render_matplotlib_with_layout(
    self, *, snapshot_id: str = "layout:matplotlib"
) -> MatplotlibProtocolRenderResult:
    """Render through Matplotlib and return the resolved layout snapshot."""
    axes_model = self.axes[0] if self.axes else None
    return render_protocol_scene_with_layout(
        visuals=self.visuals(),
        snapshot_id=snapshot_id,
        view=axes_model.view if axes_model is not None else None,
        axis_guides=tuple(axes_model.axis_guides) if axes_model is not None else (),
        panel_text_guides=tuple(axes_model.panel_text_guides)
        if axes_model is not None
        else (),
        colorbar_guides=tuple(axes_model.colorbar_guides)
        if axes_model is not None
        else (),
        color_scales={scale.id: scale for scale in self.color_scale_resources},
    )

savefig(path: str | Path, **kwargs: Any) -> None

Render through Matplotlib and save the result.

Source code in src/vispy2/protocol.py
204
205
206
207
208
209
210
211
212
def savefig(self, path: str | Path, **kwargs: Any) -> None:
    """Render through Matplotlib and save the result."""
    fig, _ = self.render_matplotlib()
    try:
        fig.savefig(path, **kwargs)
    finally:
        import matplotlib.pyplot as plt

        plt.close(fig)

show() -> tuple[Any, Any]

Render and show the Matplotlib figure.

Source code in src/vispy2/protocol.py
214
215
216
217
218
219
220
def show(self) -> tuple[Any, Any]:
    """Render and show the Matplotlib figure."""
    fig, mpl_axes = self.render_matplotlib()
    import matplotlib.pyplot as plt

    plt.show()
    return fig, mpl_axes

affine2d(matrix: npt.ArrayLike) -> VisualTransformBinding

Create an inline S027 affine 2D visual transform binding.

Source code in src/vispy2/protocol.py
928
929
930
def affine2d(matrix: npt.ArrayLike) -> VisualTransformBinding:
    """Create an inline S027 affine 2D visual transform binding."""
    return VisualTransformBinding.inline_affine(_affine_matrix(matrix))

color_scale(**kwargs: Any) -> ColorScale

Create a color scale in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
990
991
992
993
def color_scale(**kwargs: Any) -> ColorScale:
    """Create a color scale in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.color_scale(**kwargs)

colorbar(color_scale: str | ColorScale, **kwargs: Any) -> ColorbarGuide

Create a colorbar guide in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
996
997
998
999
def colorbar(color_scale: str | ColorScale, **kwargs: Any) -> ColorbarGuide:
    """Create a colorbar guide in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.colorbar(color_scale, **kwargs)

markers(x: npt.ArrayLike, y: npt.ArrayLike | None = None, **kwargs: Any) -> MarkerVisual

Create a marker visual in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
941
942
943
944
945
946
def markers(
    x: npt.ArrayLike, y: npt.ArrayLike | None = None, **kwargs: Any
) -> MarkerVisual:
    """Create a marker visual in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.markers(x, y, **kwargs)

mesh(positions: npt.ArrayLike, faces: npt.ArrayLike, **kwargs: Any) -> MeshVisual

Create a mesh visual in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
978
979
980
981
def mesh(positions: npt.ArrayLike, faces: npt.ArrayLike, **kwargs: Any) -> MeshVisual:
    """Create a mesh visual in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.mesh(positions, faces, **kwargs)

path(positions: npt.ArrayLike, **kwargs: Any) -> PathVisual

Create a path visual in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
955
956
957
958
def path(positions: npt.ArrayLike, **kwargs: Any) -> PathVisual:
    """Create a path visual in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.path(positions, **kwargs)

segments(start: npt.ArrayLike, end: npt.ArrayLike, **kwargs: Any) -> SegmentVisual

Create a segment visual in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
949
950
951
952
def segments(start: npt.ArrayLike, end: npt.ArrayLike, **kwargs: Any) -> SegmentVisual:
    """Create a segment visual in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.segments(start, end, **kwargs)

subplots() -> tuple[Figure, Axes]

Create a one-axes VisPy2 protocol figure.

Source code in src/vispy2/protocol.py
921
922
923
924
925
def subplots() -> tuple[Figure, Axes]:
    """Create a one-axes VisPy2 protocol figure."""
    fig = Figure()
    ax = fig.add_axes()
    return fig, ax

text(x: npt.ArrayLike, y: npt.ArrayLike | None, texts: str | tuple[str, ...] | list[str], **kwargs: Any) -> TextVisual

Create a text visual in a temporary one-axes figure.

Source code in src/vispy2/protocol.py
967
968
969
970
971
972
973
974
975
def text(
    x: npt.ArrayLike,
    y: npt.ArrayLike | None,
    texts: str | tuple[str, ...] | list[str],
    **kwargs: Any,
) -> TextVisual:
    """Create a text visual in a temporary one-axes figure."""
    _, ax = subplots()
    return ax.text(x, y, texts, **kwargs)

Axes Module

The axes module contains tick utility helpers only. Legacy AxesDisplay, AxesPanZoom, and AxesManaged were removed in favor of canonical View2D navigation and semantic guides.

vispy2.axes

Initialization code for the axes module.

AxisTickFormatter

Format axis tick labels based on step size and notation rules.

Parameters:

Name Type Description Default
scientific_threshold int

Minimum absolute exponent to switch to scientific notation.

3
Source code in src/vispy2/axes/axis_tick_formater.py
 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
class AxisTickFormatter:
    """Format axis tick labels based on step size and notation rules.

    Args:
        scientific_threshold (int): Minimum absolute exponent to switch to scientific notation.
    """

    def __init__(self, scientific_threshold: int = 3) -> None:
        """Initialize the formatter with a scientific notation threshold.

        Args:
            scientific_threshold (int): Exponent magnitude at which labels use scientific notation.
        """
        self.scientific_threshold: int = scientific_threshold

    def precision(self, step: float) -> int:
        """Determine the number of decimal places from the tick step.

        Args:
            step (float): Tick spacing.

        Returns:
            int: Number of decimal places to keep.
        """
        if step <= 0:
            # Avoid log10 domain errors and keep integers for degenerate steps.
            return 0
        return max(0, -math.floor(math.log10(step)))

    def format(self, tick_value: float, tick_step: float) -> str:
        """Format the tick label for a value using the step size.

        Args:
            tick_value (float): Tick value to format.
            tick_step (float): Tick spacing used to infer precision.

        Returns:
            str: Formatted tick label.
        """
        if tick_value == 0:
            return "0"

        # Determine if scientific notation is needed.
        magnitude = abs(tick_value)
        if magnitude > 0:
            order = math.floor(math.log10(magnitude))
            if abs(order) >= self.scientific_threshold:
                # Switch to scientific notation for very large/small values.
                return f"{tick_value:.0e}"

        # Standard decimal formatting based on step precision.
        decimals = self.precision(tick_step)
        return f"{tick_value:.{decimals}f}"

__init__(scientific_threshold: int = 3) -> None

Initialize the formatter with a scientific notation threshold.

Parameters:

Name Type Description Default
scientific_threshold int

Exponent magnitude at which labels use scientific notation.

3
Source code in src/vispy2/axes/axis_tick_formater.py
14
15
16
17
18
19
20
def __init__(self, scientific_threshold: int = 3) -> None:
    """Initialize the formatter with a scientific notation threshold.

    Args:
        scientific_threshold (int): Exponent magnitude at which labels use scientific notation.
    """
    self.scientific_threshold: int = scientific_threshold

precision(step: float) -> int

Determine the number of decimal places from the tick step.

Parameters:

Name Type Description Default
step float

Tick spacing.

required

Returns:

Name Type Description
int int

Number of decimal places to keep.

Source code in src/vispy2/axes/axis_tick_formater.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def precision(self, step: float) -> int:
    """Determine the number of decimal places from the tick step.

    Args:
        step (float): Tick spacing.

    Returns:
        int: Number of decimal places to keep.
    """
    if step <= 0:
        # Avoid log10 domain errors and keep integers for degenerate steps.
        return 0
    return max(0, -math.floor(math.log10(step)))

format(tick_value: float, tick_step: float) -> str

Format the tick label for a value using the step size.

Parameters:

Name Type Description Default
tick_value float

Tick value to format.

required
tick_step float

Tick spacing used to infer precision.

required

Returns:

Name Type Description
str str

Formatted tick label.

Source code in src/vispy2/axes/axis_tick_formater.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def format(self, tick_value: float, tick_step: float) -> str:
    """Format the tick label for a value using the step size.

    Args:
        tick_value (float): Tick value to format.
        tick_step (float): Tick spacing used to infer precision.

    Returns:
        str: Formatted tick label.
    """
    if tick_value == 0:
        return "0"

    # Determine if scientific notation is needed.
    magnitude = abs(tick_value)
    if magnitude > 0:
        order = math.floor(math.log10(magnitude))
        if abs(order) >= self.scientific_threshold:
            # Switch to scientific notation for very large/small values.
            return f"{tick_value:.0e}"

    # Standard decimal formatting based on step precision.
    decimals = self.precision(tick_step)
    return f"{tick_value:.{decimals}f}"

AxisTickLocator

Compute visually pleasing tick positions for an axis.

Parameters:

Name Type Description Default
target_ticks int

Desired number of ticks; treated as a hint rather than a hard requirement.

6
nice_fractions typing.Tuple[float, ...]

Ordered fractions used to snap the raw step to a human-friendly value.

(1, 2, 2.5, 5, 10)
Source code in src/vispy2/axes/axis_tick_locator.py
 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
class AxisTickLocator:
    """Compute visually pleasing tick positions for an axis.

    Args:
        target_ticks (int): Desired number of ticks; treated as a hint rather than a hard requirement.
        nice_fractions (Tuple[float, ...]): Ordered fractions used to snap the raw step to a human-friendly value.
    """

    def __init__(
        self,
        target_ticks: int = 6,
        nice_fractions: Tuple[float, ...] = (1, 2, 2.5, 5, 10),
    ) -> None:
        """Initialize the AxisTickLocator.

        Args:
            target_ticks (int): Desired number of ticks.
            nice_fractions (Tuple[float, ...]): Fractions for nice number calculation.
        """
        self.target_ticks: int = target_ticks
        self.nice_fractions: Tuple[float, ...] = nice_fractions

    def tick_step(self, min_dunit: float, max_dunit: float) -> float:
        """Return a suitable tick step for the interval.

        Args:
            min_dunit (float): Minimum data value in data unit.
            max_dunit (float): Maximum data value in data unit.

        Returns:
            float: Step size chosen to give well-spaced ticks.
        """
        if min_dunit == max_dunit:
            return self._fallback_step(min_dunit)

        data_range = abs(max_dunit - min_dunit)
        raw_step = data_range / max(1, self.target_ticks)

        # Decompose the raw step to snap it to a "nice" fraction of a power of ten.
        exponent = math.floor(math.log10(raw_step))
        base = 10**exponent
        fraction = raw_step / base

        for nice in self.nice_fractions:
            if fraction <= nice:
                return float(nice * base)

        # Fallback (should rarely happen)
        return float(self.nice_fractions[-1] * base)

    def compute_location_dunit(self, min_dunit: float, max_dunit: float) -> Tuple[List[float], float]:
        """Generate tick positions in data units and the step size for an interval.

        Args:
            min_dunit (float): Minimum data value in data unit.
            max_dunit (float): Maximum data value in data unit.

        Returns:
            Tuple[List[float], float]: List of tick positions and the step size used.
        """
        tick_step = self.tick_step(min_dunit, max_dunit)

        start = math.ceil(min_dunit / tick_step) * tick_step
        end = math.floor(max_dunit / tick_step) * tick_step

        # Keep both bounds inclusive and guard against floating-point drift.
        tick_count = int(round((end - start) / tick_step)) + 1
        tick_positions = [start + tick_index * tick_step for tick_index in range(max(0, tick_count))]

        # Final rounding pass
        tick_positions = [self._round_tick(tick_position, tick_step) for tick_position in tick_positions]

        return tick_positions, tick_step

    def _fallback_step(self, value: float) -> float:
        if value == 0:
            return 1.0
        exponent = math.floor(math.log10(abs(value)))
        return float(10**exponent)

    def _round_tick(self, tick_value: float, tick_step: float) -> float:
        decimals = max(0, -math.floor(math.log10(tick_step)))
        return round(tick_value, decimals + 2)

__init__(target_ticks: int = 6, nice_fractions: Tuple[float, ...] = (1, 2, 2.5, 5, 10)) -> None

Initialize the AxisTickLocator.

Parameters:

Name Type Description Default
target_ticks int

Desired number of ticks.

6
nice_fractions typing.Tuple[float, ...]

Fractions for nice number calculation.

(1, 2, 2.5, 5, 10)
Source code in src/vispy2/axes/axis_tick_locator.py
16
17
18
19
20
21
22
23
24
25
26
27
28
def __init__(
    self,
    target_ticks: int = 6,
    nice_fractions: Tuple[float, ...] = (1, 2, 2.5, 5, 10),
) -> None:
    """Initialize the AxisTickLocator.

    Args:
        target_ticks (int): Desired number of ticks.
        nice_fractions (Tuple[float, ...]): Fractions for nice number calculation.
    """
    self.target_ticks: int = target_ticks
    self.nice_fractions: Tuple[float, ...] = nice_fractions

tick_step(min_dunit: float, max_dunit: float) -> float

Return a suitable tick step for the interval.

Parameters:

Name Type Description Default
min_dunit float

Minimum data value in data unit.

required
max_dunit float

Maximum data value in data unit.

required

Returns:

Name Type Description
float float

Step size chosen to give well-spaced ticks.

Source code in src/vispy2/axes/axis_tick_locator.py
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
def tick_step(self, min_dunit: float, max_dunit: float) -> float:
    """Return a suitable tick step for the interval.

    Args:
        min_dunit (float): Minimum data value in data unit.
        max_dunit (float): Maximum data value in data unit.

    Returns:
        float: Step size chosen to give well-spaced ticks.
    """
    if min_dunit == max_dunit:
        return self._fallback_step(min_dunit)

    data_range = abs(max_dunit - min_dunit)
    raw_step = data_range / max(1, self.target_ticks)

    # Decompose the raw step to snap it to a "nice" fraction of a power of ten.
    exponent = math.floor(math.log10(raw_step))
    base = 10**exponent
    fraction = raw_step / base

    for nice in self.nice_fractions:
        if fraction <= nice:
            return float(nice * base)

    # Fallback (should rarely happen)
    return float(self.nice_fractions[-1] * base)

compute_location_dunit(min_dunit: float, max_dunit: float) -> Tuple[List[float], float]

Generate tick positions in data units and the step size for an interval.

Parameters:

Name Type Description Default
min_dunit float

Minimum data value in data unit.

required
max_dunit float

Maximum data value in data unit.

required

Returns:

Type Description
typing.Tuple[typing.List[float], float]

Tuple[List[float], float]: List of tick positions and the step size used.

Source code in src/vispy2/axes/axis_tick_locator.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def compute_location_dunit(self, min_dunit: float, max_dunit: float) -> Tuple[List[float], float]:
    """Generate tick positions in data units and the step size for an interval.

    Args:
        min_dunit (float): Minimum data value in data unit.
        max_dunit (float): Maximum data value in data unit.

    Returns:
        Tuple[List[float], float]: List of tick positions and the step size used.
    """
    tick_step = self.tick_step(min_dunit, max_dunit)

    start = math.ceil(min_dunit / tick_step) * tick_step
    end = math.floor(max_dunit / tick_step) * tick_step

    # Keep both bounds inclusive and guard against floating-point drift.
    tick_count = int(round((end - start) / tick_step)) + 1
    tick_positions = [start + tick_index * tick_step for tick_index in range(max(0, tick_count))]

    # Final rounding pass
    tick_positions = [self._round_tick(tick_position, tick_step) for tick_position in tick_positions]

    return tick_positions, tick_step