Skip to content

Visualization Module / 可視化モジュール

The wandas.visualization module provides plotting and presentation helpers for Frame results.

wandas.visualizationはFrame結果のplotと表示helperを提供します。

wandas.visualization.plotting

Attributes

logger = logging.getLogger(__name__) module-attribute

TFrame = TypeVar('TFrame', bound='BaseFrame[Any]') module-attribute

PlotLabel = str | Sequence[str] | None module-attribute

Classes

PlotStrategy

Bases: ABC, Generic[TFrame]

Base class for plotting strategies

Source code in wandas/visualization/plotting.py
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
class PlotStrategy(abc.ABC, Generic[TFrame]):
    """Base class for plotting strategies"""

    name: ClassVar[str]

    @abc.abstractmethod
    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
    ) -> None:
        """Implementation of channel plotting"""

    @abc.abstractmethod
    def plot(
        self,
        bf: TFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """Implementation of plotting"""
Attributes
name class-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0) abstractmethod

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
109
110
111
112
113
114
115
116
117
118
@abc.abstractmethod
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
) -> None:
    """Implementation of channel plotting"""
plot(bf, ax=None, title=None, overlay=False, **kwargs) abstractmethod

Implementation of plotting

Source code in wandas/visualization/plotting.py
120
121
122
123
124
125
126
127
128
129
@abc.abstractmethod
def plot(
    self,
    bf: TFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """Implementation of plotting"""

WaveformPlotStrategy

Bases: PlotStrategy['ChannelFrame']

Strategy for waveform plotting

Source code in wandas/visualization/plotting.py
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
class WaveformPlotStrategy(PlotStrategy["ChannelFrame"]):
    """Strategy for waveform plotting"""

    name = "waveform"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        """Implementation of channel plotting"""
        if label is not None:
            kwargs["label"] = label
        if alpha is not None:
            kwargs["alpha"] = alpha
        ax.plot(x, y, **kwargs)
        ax.set_ylabel("Amplitude")
        ax.grid(True)
        if label is not None:
            ax.legend()

    def plot(
        self,
        bf: ChannelFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """Waveform plotting"""
        kwargs = kwargs or {}
        axes_cls = _matplotlib_axes_type("waveform plot")
        line2d_cls = _matplotlib_line2d_type("waveform plot")
        explicit_ylabel = "ylabel" in kwargs
        append_channel_units = kwargs.pop("_append_channel_units", not explicit_ylabel)
        ylabel = kwargs.pop("ylabel", "Amplitude")
        xlabel = kwargs.pop("xlabel", "Time [s]")
        alpha = kwargs.pop("alpha", 1)
        label = kwargs.pop("label", None)
        max_points = _validate_max_points(kwargs.pop("max_points", _AUTO_MAX_POINTS))
        plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
        ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)
        data = _reshape_to_2d(bf.data)
        time = bf.time
        lines_drawn = None
        if max_points is not None:
            envelope = _MinMaxEnvelope(np.asarray(time), np.asarray(data), max_points)
            # A nonlinear axes keeps every sample, and autoscales from the smallest positive sample.
            if max_points != _AUTO_MAX_POINTS or ax is None or _has_linear_scales(ax):
                time, data = envelope.reduce(None, envelope.budget(ax))
            lines_drawn = envelope.track
        channel_units = [ch_meta.unit for ch_meta in bf.channels]
        all_level_units = bool(channel_units) and all(unit.startswith("dB ") for unit in channel_units)
        if not explicit_ylabel and all_level_units:
            ylabel = "Level"

        def _waveform_ylabel(ylabel: str, ch_meta: Any) -> str:
            if not append_channel_units:
                return ylabel
            unit_suffix = f" [{ch_meta.unit}]" if ch_meta.unit else ""
            return f"{ylabel}{unit_suffix}"

        if (overlay or ax is not None) and append_channel_units:
            if channel_units and all(unit and unit == channel_units[0] for unit in channel_units):
                ylabel = f"{ylabel} [{channel_units[0]}]"
            elif all_level_units:
                ylabel = f"{ylabel} [dB re channel reference]"

        return _plot_line_layout(
            self,
            bf,
            time,
            data,
            ax=ax,
            title=title,
            overlay=overlay,
            ylabel=ylabel,
            xlabel=xlabel,
            default_title=bf.label or "Channel Data",
            alpha=alpha,
            label=label,
            plot_kwargs=plot_kwargs,
            ax_set=ax_set,
            per_channel_ylabel_fn=_waveform_ylabel,
            lines_drawn=lines_drawn,
        )
Attributes
name = 'waveform' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    """Implementation of channel plotting"""
    if label is not None:
        kwargs["label"] = label
    if alpha is not None:
        kwargs["alpha"] = alpha
    ax.plot(x, y, **kwargs)
    ax.set_ylabel("Amplitude")
    ax.grid(True)
    if label is not None:
        ax.legend()
plot(bf, ax=None, title=None, overlay=False, **kwargs)

Waveform plotting

Source code in wandas/visualization/plotting.py
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
def plot(
    self,
    bf: ChannelFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """Waveform plotting"""
    kwargs = kwargs or {}
    axes_cls = _matplotlib_axes_type("waveform plot")
    line2d_cls = _matplotlib_line2d_type("waveform plot")
    explicit_ylabel = "ylabel" in kwargs
    append_channel_units = kwargs.pop("_append_channel_units", not explicit_ylabel)
    ylabel = kwargs.pop("ylabel", "Amplitude")
    xlabel = kwargs.pop("xlabel", "Time [s]")
    alpha = kwargs.pop("alpha", 1)
    label = kwargs.pop("label", None)
    max_points = _validate_max_points(kwargs.pop("max_points", _AUTO_MAX_POINTS))
    plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
    ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)
    data = _reshape_to_2d(bf.data)
    time = bf.time
    lines_drawn = None
    if max_points is not None:
        envelope = _MinMaxEnvelope(np.asarray(time), np.asarray(data), max_points)
        # A nonlinear axes keeps every sample, and autoscales from the smallest positive sample.
        if max_points != _AUTO_MAX_POINTS or ax is None or _has_linear_scales(ax):
            time, data = envelope.reduce(None, envelope.budget(ax))
        lines_drawn = envelope.track
    channel_units = [ch_meta.unit for ch_meta in bf.channels]
    all_level_units = bool(channel_units) and all(unit.startswith("dB ") for unit in channel_units)
    if not explicit_ylabel and all_level_units:
        ylabel = "Level"

    def _waveform_ylabel(ylabel: str, ch_meta: Any) -> str:
        if not append_channel_units:
            return ylabel
        unit_suffix = f" [{ch_meta.unit}]" if ch_meta.unit else ""
        return f"{ylabel}{unit_suffix}"

    if (overlay or ax is not None) and append_channel_units:
        if channel_units and all(unit and unit == channel_units[0] for unit in channel_units):
            ylabel = f"{ylabel} [{channel_units[0]}]"
        elif all_level_units:
            ylabel = f"{ylabel} [dB re channel reference]"

    return _plot_line_layout(
        self,
        bf,
        time,
        data,
        ax=ax,
        title=title,
        overlay=overlay,
        ylabel=ylabel,
        xlabel=xlabel,
        default_title=bf.label or "Channel Data",
        alpha=alpha,
        label=label,
        plot_kwargs=plot_kwargs,
        ax_set=ax_set,
        per_channel_ylabel_fn=_waveform_ylabel,
        lines_drawn=lines_drawn,
    )

FrequencyPlotStrategy

Bases: PlotStrategy['SpectralFrame']

Strategy for frequency domain plotting

Source code in wandas/visualization/plotting.py
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
class FrequencyPlotStrategy(PlotStrategy["SpectralFrame"]):
    """Strategy for frequency domain plotting"""

    name = "frequency"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        """Implementation of channel plotting"""
        if label is not None:
            kwargs["label"] = label
        if alpha is not None and alpha != 1.0:
            kwargs["alpha"] = alpha
        ax.plot(x, y, **kwargs)
        ax.grid(True)
        if label is not None:
            ax.legend()

    def plot(
        self,
        bf: SpectralFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """Frequency domain plotting"""
        kwargs = kwargs or {}
        axes_cls = _matplotlib_axes_type("frequency plot")
        line2d_cls = _matplotlib_line2d_type("frequency plot")
        is_aw = kwargs.pop("Aw", False)
        view = kwargs.pop("view", None)
        typed_values = _typed_frequency_values(bf, view=view, aw=is_aw)
        if typed_values is not None:
            data, default_ylabel = typed_values
            ylabel = kwargs.pop("ylabel", default_ylabel)
        else:
            if view is not None:
                raise ValueError(
                    "The 'view' argument is supported only by a typed quantity Frame; "
                    "ordinary SpectralFrame plotting uses its amplitude level."
                )
            data = bf.dBA if is_aw else bf.dB
            default_ylabel = (
                "A-weighted amplitude level [dB re channel ref]" if is_aw else "Amplitude level [dB re channel ref]"
            )
            ylabel = kwargs.pop("ylabel", default_ylabel)
        data = _reshape_to_2d(data)
        xlabel = kwargs.pop("xlabel", "Frequency [Hz]")
        alpha = kwargs.pop("alpha", 1)
        label = kwargs.pop("label", None)
        plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
        ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

        return _plot_line_layout(
            self,
            bf,
            bf.freqs,
            data,
            ax=ax,
            title=title,
            overlay=overlay,
            ylabel=ylabel,
            xlabel=xlabel,
            default_title=bf.label or "Channel Data",
            alpha=alpha,
            label=label,
            plot_kwargs=plot_kwargs,
            ax_set=ax_set,
        )
Attributes
name = 'frequency' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    """Implementation of channel plotting"""
    if label is not None:
        kwargs["label"] = label
    if alpha is not None and alpha != 1.0:
        kwargs["alpha"] = alpha
    ax.plot(x, y, **kwargs)
    ax.grid(True)
    if label is not None:
        ax.legend()
plot(bf, ax=None, title=None, overlay=False, **kwargs)

Frequency domain plotting

Source code in wandas/visualization/plotting.py
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
def plot(
    self,
    bf: SpectralFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """Frequency domain plotting"""
    kwargs = kwargs or {}
    axes_cls = _matplotlib_axes_type("frequency plot")
    line2d_cls = _matplotlib_line2d_type("frequency plot")
    is_aw = kwargs.pop("Aw", False)
    view = kwargs.pop("view", None)
    typed_values = _typed_frequency_values(bf, view=view, aw=is_aw)
    if typed_values is not None:
        data, default_ylabel = typed_values
        ylabel = kwargs.pop("ylabel", default_ylabel)
    else:
        if view is not None:
            raise ValueError(
                "The 'view' argument is supported only by a typed quantity Frame; "
                "ordinary SpectralFrame plotting uses its amplitude level."
            )
        data = bf.dBA if is_aw else bf.dB
        default_ylabel = (
            "A-weighted amplitude level [dB re channel ref]" if is_aw else "Amplitude level [dB re channel ref]"
        )
        ylabel = kwargs.pop("ylabel", default_ylabel)
    data = _reshape_to_2d(data)
    xlabel = kwargs.pop("xlabel", "Frequency [Hz]")
    alpha = kwargs.pop("alpha", 1)
    label = kwargs.pop("label", None)
    plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
    ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

    return _plot_line_layout(
        self,
        bf,
        bf.freqs,
        data,
        ax=ax,
        title=title,
        overlay=overlay,
        ylabel=ylabel,
        xlabel=xlabel,
        default_title=bf.label or "Channel Data",
        alpha=alpha,
        label=label,
        plot_kwargs=plot_kwargs,
        ax_set=ax_set,
    )

NOctPlotStrategy

Bases: PlotStrategy['NOctFrame']

Strategy for N-octave band analysis plotting

Source code in wandas/visualization/plotting.py
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
class NOctPlotStrategy(PlotStrategy["NOctFrame"]):
    """Strategy for N-octave band analysis plotting"""

    name = "noct"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        """Implementation of channel plotting"""
        if label is not None:
            kwargs["label"] = label
        if alpha is not None and alpha != 1.0:
            kwargs["alpha"] = alpha
        ax.step(x, y, **kwargs)
        ax.grid(True)
        if label is not None:
            ax.legend()

    def plot(
        self,
        bf: NOctFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """N-octave band analysis plotting"""
        kwargs = kwargs or {}
        axes_cls = _matplotlib_axes_type("noct plot")
        line2d_cls = _matplotlib_line2d_type("noct plot")
        is_aw = kwargs.pop("Aw", False)

        if is_aw:
            data = bf.dBA
            default_ylabel = "A-weighted band RMS level [dB re channel ref]"
        else:
            data = bf.dB
            default_ylabel = "Band RMS level [dB re channel ref]"
        data = _reshape_to_2d(data)
        ylabel = kwargs.pop("ylabel", default_ylabel)
        xlabel = kwargs.pop("xlabel", "Center frequency [Hz]")
        alpha = kwargs.pop("alpha", 1)
        label = kwargs.pop("label", None)
        plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
        ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

        default_title = bf.label or f"1/{bf.n!s}-Octave Spectrum"
        return _plot_line_layout(
            self,
            bf,
            bf.freqs,
            data,
            ax=ax,
            title=title,
            overlay=overlay,
            ylabel=ylabel,
            xlabel=xlabel,
            default_title=default_title,
            alpha=alpha,
            label=label,
            plot_kwargs=plot_kwargs,
            ax_set=ax_set,
        )
Attributes
name = 'noct' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    """Implementation of channel plotting"""
    if label is not None:
        kwargs["label"] = label
    if alpha is not None and alpha != 1.0:
        kwargs["alpha"] = alpha
    ax.step(x, y, **kwargs)
    ax.grid(True)
    if label is not None:
        ax.legend()
plot(bf, ax=None, title=None, overlay=False, **kwargs)

N-octave band analysis plotting

Source code in wandas/visualization/plotting.py
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
def plot(
    self,
    bf: NOctFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """N-octave band analysis plotting"""
    kwargs = kwargs or {}
    axes_cls = _matplotlib_axes_type("noct plot")
    line2d_cls = _matplotlib_line2d_type("noct plot")
    is_aw = kwargs.pop("Aw", False)

    if is_aw:
        data = bf.dBA
        default_ylabel = "A-weighted band RMS level [dB re channel ref]"
    else:
        data = bf.dB
        default_ylabel = "Band RMS level [dB re channel ref]"
    data = _reshape_to_2d(data)
    ylabel = kwargs.pop("ylabel", default_ylabel)
    xlabel = kwargs.pop("xlabel", "Center frequency [Hz]")
    alpha = kwargs.pop("alpha", 1)
    label = kwargs.pop("label", None)
    plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
    ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

    default_title = bf.label or f"1/{bf.n!s}-Octave Spectrum"
    return _plot_line_layout(
        self,
        bf,
        bf.freqs,
        data,
        ax=ax,
        title=title,
        overlay=overlay,
        ylabel=ylabel,
        xlabel=xlabel,
        default_title=default_title,
        alpha=alpha,
        label=label,
        plot_kwargs=plot_kwargs,
        ax_set=ax_set,
    )

SpectrogramPlotStrategy

Bases: PlotStrategy['SpectrogramFrame']

Strategy for spectrogram plotting

Source code in wandas/visualization/plotting.py
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
class SpectrogramPlotStrategy(PlotStrategy["SpectrogramFrame"]):
    """Strategy for spectrogram plotting"""

    name = "spectrogram"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        """Implementation of channel plotting"""

    def plot(
        self,
        bf: SpectrogramFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """Spectrogram plotting"""
        # Explicit overlay mode is not supported for spectrograms
        if overlay:
            raise ValueError("Overlay is not supported for SpectrogramPlotStrategy.")

        # If an Axes is provided, allow drawing into it only for single-channel frames
        if ax is not None and bf.n_channels > 1:
            raise ValueError("ax must be None when n_channels > 1.")

        kwargs = kwargs or {}
        plt = _matplotlib_pyplot("spectrogram plot")
        axes_cls = _matplotlib_axes_type("spectrogram plot")
        figure_cls = _matplotlib_figure_type("spectrogram plot")

        is_aw = kwargs.pop("Aw", False)
        if is_aw:
            unit = "dBA"
            data = bf.dBA
        else:
            unit = "dB"
            data = bf.dB
        data = _reshape_spectrogram_data(data)

        cmap = kwargs.pop("cmap", "jet")
        vmin = kwargs.pop("vmin", None)
        vmax = kwargs.pop("vmax", None)
        fmin = kwargs.pop("fmin", 0)
        fmax = kwargs.pop("fmax", None)
        xlim = kwargs.pop("xlim", None)
        ylim = kwargs.pop("ylim", None)
        shading = kwargs.pop("shading", "auto")
        ax_set_kwargs = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

        def draw_spectrogram(target_ax: Axes, channel_data: np.ndarray, plot_title: str | None) -> Any:
            times, freqs = _spectrogram_axis_values(bf, channel_data)
            image_kwargs = filter_kwargs(target_ax.pcolormesh, kwargs, strict_mode=True)
            img = target_ax.pcolormesh(
                times,
                freqs,
                channel_data,
                shading=shading,
                cmap=cmap,
                vmin=vmin,
                vmax=vmax,
                **image_kwargs,
            )
            spectrogram_ylim = ylim if ylim is not None else (fmin, fmax) if fmin != 0 or fmax is not None else None
            target_ax.set(
                title=plot_title,
                ylabel="Frequency [Hz]",
                xlabel="Time [s]",
                xlim=xlim,
                ylim=spectrogram_ylim,
                **ax_set_kwargs,
            )
            return img

        if ax is not None:
            img = draw_spectrogram(ax, data[0], title or bf.label or "Spectrogram")

            fig = ax.figure
            if fig is not None:
                try:
                    cbar = fig.colorbar(img, ax=ax)
                    cbar.set_label(f"Spectrum level [{unit}]")
                except (ValueError, AttributeError) as e:
                    logger.warning(f"Failed to create colorbar for spectrogram: {type(e).__name__}: {e}")
            return ax

        # Create a new figure if ax is None
        num_channels = bf.n_channels
        fig, axs = plt.subplots(num_channels, 1, figsize=(10, 5 * num_channels), sharex=True)
        if not isinstance(fig, figure_cls):
            raise ValueError("fig must be a matplotlib Figure object.")
        # Convert axs to array if it is a single Axes object
        if not isinstance(axs, np.ndarray):
            axs = np.array([axs])

        for ax_i, channel_data, ch_meta in zip(axs.flatten(), data, bf.channels, strict=True):
            img = draw_spectrogram(ax_i, channel_data, ch_meta.label)
            try:
                cbar = ax_i.figure.colorbar(img, ax=ax_i)
                cbar.set_label(f"Spectrum level [{unit}]")
            except (ValueError, AttributeError) as e:
                logger.warning(f"Failed to create colorbar for spectrogram: {type(e).__name__}: {e}")
            fig.suptitle(title or "Spectrogram Data")
        plt.tight_layout()
        notebook.show_figure(fig)

        return _return_axes_iterator(fig.axes)
Attributes
name = 'spectrogram' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
771
772
773
774
775
776
777
778
779
780
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    """Implementation of channel plotting"""
plot(bf, ax=None, title=None, overlay=False, **kwargs)

Spectrogram plotting

Source code in wandas/visualization/plotting.py
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
def plot(
    self,
    bf: SpectrogramFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """Spectrogram plotting"""
    # Explicit overlay mode is not supported for spectrograms
    if overlay:
        raise ValueError("Overlay is not supported for SpectrogramPlotStrategy.")

    # If an Axes is provided, allow drawing into it only for single-channel frames
    if ax is not None and bf.n_channels > 1:
        raise ValueError("ax must be None when n_channels > 1.")

    kwargs = kwargs or {}
    plt = _matplotlib_pyplot("spectrogram plot")
    axes_cls = _matplotlib_axes_type("spectrogram plot")
    figure_cls = _matplotlib_figure_type("spectrogram plot")

    is_aw = kwargs.pop("Aw", False)
    if is_aw:
        unit = "dBA"
        data = bf.dBA
    else:
        unit = "dB"
        data = bf.dB
    data = _reshape_spectrogram_data(data)

    cmap = kwargs.pop("cmap", "jet")
    vmin = kwargs.pop("vmin", None)
    vmax = kwargs.pop("vmax", None)
    fmin = kwargs.pop("fmin", 0)
    fmax = kwargs.pop("fmax", None)
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    shading = kwargs.pop("shading", "auto")
    ax_set_kwargs = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

    def draw_spectrogram(target_ax: Axes, channel_data: np.ndarray, plot_title: str | None) -> Any:
        times, freqs = _spectrogram_axis_values(bf, channel_data)
        image_kwargs = filter_kwargs(target_ax.pcolormesh, kwargs, strict_mode=True)
        img = target_ax.pcolormesh(
            times,
            freqs,
            channel_data,
            shading=shading,
            cmap=cmap,
            vmin=vmin,
            vmax=vmax,
            **image_kwargs,
        )
        spectrogram_ylim = ylim if ylim is not None else (fmin, fmax) if fmin != 0 or fmax is not None else None
        target_ax.set(
            title=plot_title,
            ylabel="Frequency [Hz]",
            xlabel="Time [s]",
            xlim=xlim,
            ylim=spectrogram_ylim,
            **ax_set_kwargs,
        )
        return img

    if ax is not None:
        img = draw_spectrogram(ax, data[0], title or bf.label or "Spectrogram")

        fig = ax.figure
        if fig is not None:
            try:
                cbar = fig.colorbar(img, ax=ax)
                cbar.set_label(f"Spectrum level [{unit}]")
            except (ValueError, AttributeError) as e:
                logger.warning(f"Failed to create colorbar for spectrogram: {type(e).__name__}: {e}")
        return ax

    # Create a new figure if ax is None
    num_channels = bf.n_channels
    fig, axs = plt.subplots(num_channels, 1, figsize=(10, 5 * num_channels), sharex=True)
    if not isinstance(fig, figure_cls):
        raise ValueError("fig must be a matplotlib Figure object.")
    # Convert axs to array if it is a single Axes object
    if not isinstance(axs, np.ndarray):
        axs = np.array([axs])

    for ax_i, channel_data, ch_meta in zip(axs.flatten(), data, bf.channels, strict=True):
        img = draw_spectrogram(ax_i, channel_data, ch_meta.label)
        try:
            cbar = ax_i.figure.colorbar(img, ax=ax_i)
            cbar.set_label(f"Spectrum level [{unit}]")
        except (ValueError, AttributeError) as e:
            logger.warning(f"Failed to create colorbar for spectrogram: {type(e).__name__}: {e}")
        fig.suptitle(title or "Spectrogram Data")
    plt.tight_layout()
    notebook.show_figure(fig)

    return _return_axes_iterator(fig.axes)

DescribePlotStrategy

Bases: PlotStrategy['ChannelFrame']

Strategy for visualizing ChannelFrame data with describe plot

Source code in wandas/visualization/plotting.py
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
class DescribePlotStrategy(PlotStrategy["ChannelFrame"]):
    """Strategy for visualizing ChannelFrame data with describe plot"""

    name = "describe"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        """Implementation of channel plotting"""
        # This method is not used for describe plot

    def plot(
        self,
        bf: ChannelFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        """Implementation of describe method for visualizing ChannelFrame data"""

        plt = _matplotlib_pyplot("describe plot")
        gridspec = _matplotlib_gridspec("describe plot")

        fmin = kwargs.pop("fmin", 0)
        fmax = kwargs.pop("fmax", None)
        cmap = kwargs.pop("cmap", "jet")
        vmin = kwargs.pop("vmin", None)
        vmax = kwargs.pop("vmax", None)
        xlim = kwargs.pop("xlim", None)
        ylim = kwargs.pop("ylim", None)
        is_aw = kwargs.pop("Aw", False)
        waveform = kwargs.pop("waveform", {})
        spectral = kwargs.pop("spectral", {"xlim": (vmin, vmax)})

        gs = gridspec.GridSpec(2, 3, height_ratios=[1, 3], width_ratios=[3, 1, 0.1])
        gs.update(wspace=0.2)

        fig = plt.figure(figsize=(12, 6))
        fig.subplots_adjust(wspace=0.0001)

        # First subplot (Time Plot)
        ax_1 = fig.add_subplot(gs[0])
        bf.plot(plot_type="waveform", ax=ax_1, overlay=True)
        ax_1.set(**waveform)
        ax_1.legend().set_visible(False)
        ax_1.set(xlabel="", title="")

        # Second subplot (STFT Plot)
        ax_2 = fig.add_subplot(gs[3], sharex=ax_1)
        stft_ch = bf.stft()
        if is_aw:
            unit = "dBA"
            channel_data = stft_ch.dBA
        else:
            unit = "dB"
            channel_data = stft_ch.dB
        if channel_data.ndim == 3:
            channel_data = channel_data[0]
        # Get the maximum value of the data and round it to a convenient value
        if vmax is None:
            data_max = np.nanmax(channel_data)
            # Round to a convenient number with increments of 10, 5, or 2
            for step in [10, 5, 2]:
                rounded_max = np.ceil(data_max / step) * step
                if rounded_max >= data_max:
                    vmax = rounded_max
                    vmin = vmax - 180
                    break
        times, freqs = _spectrogram_axis_values(stft_ch, channel_data)
        img = ax_2.pcolormesh(times, freqs, channel_data, shading="auto", cmap=cmap, vmin=vmin, vmax=vmax)
        spectrogram_ylim = ylim if ylim is not None else (fmin, fmax) if fmin != 0 or fmax is not None else None
        ax_2.set(xlabel="Time [s]", ylabel="Frequency [Hz]", xlim=xlim, ylim=spectrogram_ylim)

        # Third subplot
        ax_3 = fig.add_subplot(gs[1])
        ax_3.axis("off")

        # Fourth subplot (Welch Plot)
        ax_4 = fig.add_subplot(gs[4], sharey=ax_2)
        welch_ch = bf.welch()
        if is_aw:
            unit = "dBA"
            data_db = welch_ch.dBA
        else:
            unit = "dB"
            data_db = welch_ch.dB
        ax_4.plot(data_db.T, welch_ch.freqs.T)
        ax_4.grid(True)
        ax_4.set(xlabel=f"Spectrum level [{unit}]", **spectral)

        cbar = fig.colorbar(img, ax=ax_4, format="%+2.0f")
        cbar.set_label(unit)
        fig.suptitle(title or bf.label or "Channel Data")

        return _return_axes_iterator(fig.axes)
Attributes
name = 'describe' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)

Implementation of channel plotting

Source code in wandas/visualization/plotting.py
887
888
889
890
891
892
893
894
895
896
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    """Implementation of channel plotting"""
plot(bf, ax=None, title=None, overlay=False, **kwargs)

Implementation of describe method for visualizing ChannelFrame data

Source code in wandas/visualization/plotting.py
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
def plot(
    self,
    bf: ChannelFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    """Implementation of describe method for visualizing ChannelFrame data"""

    plt = _matplotlib_pyplot("describe plot")
    gridspec = _matplotlib_gridspec("describe plot")

    fmin = kwargs.pop("fmin", 0)
    fmax = kwargs.pop("fmax", None)
    cmap = kwargs.pop("cmap", "jet")
    vmin = kwargs.pop("vmin", None)
    vmax = kwargs.pop("vmax", None)
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    is_aw = kwargs.pop("Aw", False)
    waveform = kwargs.pop("waveform", {})
    spectral = kwargs.pop("spectral", {"xlim": (vmin, vmax)})

    gs = gridspec.GridSpec(2, 3, height_ratios=[1, 3], width_ratios=[3, 1, 0.1])
    gs.update(wspace=0.2)

    fig = plt.figure(figsize=(12, 6))
    fig.subplots_adjust(wspace=0.0001)

    # First subplot (Time Plot)
    ax_1 = fig.add_subplot(gs[0])
    bf.plot(plot_type="waveform", ax=ax_1, overlay=True)
    ax_1.set(**waveform)
    ax_1.legend().set_visible(False)
    ax_1.set(xlabel="", title="")

    # Second subplot (STFT Plot)
    ax_2 = fig.add_subplot(gs[3], sharex=ax_1)
    stft_ch = bf.stft()
    if is_aw:
        unit = "dBA"
        channel_data = stft_ch.dBA
    else:
        unit = "dB"
        channel_data = stft_ch.dB
    if channel_data.ndim == 3:
        channel_data = channel_data[0]
    # Get the maximum value of the data and round it to a convenient value
    if vmax is None:
        data_max = np.nanmax(channel_data)
        # Round to a convenient number with increments of 10, 5, or 2
        for step in [10, 5, 2]:
            rounded_max = np.ceil(data_max / step) * step
            if rounded_max >= data_max:
                vmax = rounded_max
                vmin = vmax - 180
                break
    times, freqs = _spectrogram_axis_values(stft_ch, channel_data)
    img = ax_2.pcolormesh(times, freqs, channel_data, shading="auto", cmap=cmap, vmin=vmin, vmax=vmax)
    spectrogram_ylim = ylim if ylim is not None else (fmin, fmax) if fmin != 0 or fmax is not None else None
    ax_2.set(xlabel="Time [s]", ylabel="Frequency [Hz]", xlim=xlim, ylim=spectrogram_ylim)

    # Third subplot
    ax_3 = fig.add_subplot(gs[1])
    ax_3.axis("off")

    # Fourth subplot (Welch Plot)
    ax_4 = fig.add_subplot(gs[4], sharey=ax_2)
    welch_ch = bf.welch()
    if is_aw:
        unit = "dBA"
        data_db = welch_ch.dBA
    else:
        unit = "dB"
        data_db = welch_ch.dB
    ax_4.plot(data_db.T, welch_ch.freqs.T)
    ax_4.grid(True)
    ax_4.set(xlabel=f"Spectrum level [{unit}]", **spectral)

    cbar = fig.colorbar(img, ax=ax_4, format="%+2.0f")
    cbar.set_label(unit)
    fig.suptitle(title or bf.label or "Channel Data")

    return _return_axes_iterator(fig.axes)

MatrixPlotStrategy

Bases: PlotStrategy['SpectralFrame']

Strategy for displaying relationships between channels in matrix format

Source code in wandas/visualization/plotting.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
class MatrixPlotStrategy(PlotStrategy["SpectralFrame"]):
    """Strategy for displaying relationships between channels in matrix format"""

    name = "matrix"

    def channel_plot(
        self,
        x: Any,
        y: Any,
        ax: Axes,
        label: PlotLabel = None,
        alpha: float = 1.0,
        **kwargs: Any,
    ) -> None:
        # Work on a local copy to avoid mutating caller-provided kwargs
        plot_kwargs = dict(kwargs)

        # Extract axes settings from kwargs copy
        title = plot_kwargs.pop("title", None)
        ylabel = plot_kwargs.pop("ylabel", None)
        xlabel = plot_kwargs.pop("xlabel", "Frequency [Hz]")

        if label is not None:
            plot_kwargs["label"] = label
        if alpha is not None and alpha != 1.0:
            plot_kwargs["alpha"] = alpha
        ax.plot(x, y, **plot_kwargs)
        ax.grid(True)
        if title is not None:
            ax.set_title(title)
        if ylabel is not None:
            ax.set_ylabel(ylabel)
        ax.set_xlabel(xlabel)
        if label is not None:
            ax.legend()

    def plot(
        self,
        bf: SpectralFrame,
        ax: Axes | None = None,
        title: str | None = None,
        overlay: bool = False,
        **kwargs: Any,
    ) -> Axes | Iterator[Axes]:
        kwargs = kwargs or {}
        plt = _matplotlib_pyplot("matrix plot")
        axes_cls = _matplotlib_axes_type("matrix plot")
        line2d_cls = _matplotlib_line2d_type("matrix plot")
        is_aw = kwargs.pop("Aw", False)
        view = kwargs.pop("view", None)
        typed_entries = _typed_matrix_entries(bf, view=view, aw=is_aw)
        if typed_entries is not None:
            typed_ylabel = _typed_plot_ylabel(bf, view=view, aw=is_aw)
            if typed_ylabel is None:
                typed_values = _typed_frequency_values(bf, view=view, aw=is_aw)
                if typed_values is None:
                    raise TypeError(f"{type(bf).__name__} exposes matrix entries without a frequency plotting contract")
                _, default_ylabel = typed_values
            else:
                default_ylabel = typed_ylabel
            ylabel = kwargs.pop("ylabel", default_ylabel)
        else:
            if view is not None:
                raise ValueError(
                    "The 'view' argument is supported only by a typed quantity Frame; "
                    "ordinary SpectralFrame plotting uses its amplitude level."
                )
            if is_aw:
                data = bf.dBA
                default_ylabel = "A-weighted amplitude level [dB re channel ref]"
            else:
                data = bf.dB
                default_ylabel = "Amplitude level [dB re channel ref]"
            data = _reshape_to_2d(data)
            ylabel = kwargs.pop("ylabel", default_ylabel)

        xlabel = kwargs.pop("xlabel", "Frequency [Hz]")
        alpha = kwargs.pop("alpha", 1)
        plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
        ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

        # If an Axes is provided, prefer drawing into it (treat as overlay)
        if ax is not None:
            overlay = True
        if overlay:
            created_figure = ax is None
            if ax is None:
                fig, ax = plt.subplots(1, 1, figsize=(6, 6))
            else:
                fig = ax.figure
            if ax is None:
                raise RuntimeError(  # pragma: no cover
                    "Matplotlib did not provide an Axes for matrix plotting"
                )
            if typed_entries is None:
                self.channel_plot(
                    bf.freqs,
                    data.T,
                    ax,  # Always Axes type here
                    title=title or bf.label or "Spectral Data",
                    ylabel=ylabel,
                    xlabel=xlabel,
                    alpha=alpha,
                    **plot_kwargs,
                )
            else:
                for output_index, input_index, channel_data, pair_label in typed_entries:
                    del output_index, input_index
                    self.channel_plot(
                        bf.freqs,
                        channel_data,
                        ax,
                        label=pair_label,
                        title=title or bf.label or "Spectral Data",
                        ylabel=ylabel,
                        xlabel=xlabel,
                        alpha=alpha,
                        **plot_kwargs,
                    )
            ax.set(**ax_set)
            if fig is not None:
                fig.suptitle(title or bf.label or "Spectral Data")
            if ax.figure != fig:  # Only show if we created the figure
                plt.tight_layout()
                notebook.show_figure(cast("Figure", fig))
            elif created_figure:
                notebook.display_new_figure(cast("Figure", fig))
            return cast("Axes", ax)

        if typed_entries is not None:
            source_count = int(getattr(bf, "n_source_channels", 0))
            if source_count <= 0:
                raise ValueError("A typed pairwise matrix requires at least one source channel")
            fig, axs = plt.subplots(
                source_count,
                source_count,
                figsize=(3 * source_count, 3 * source_count),
                sharex=True,
                sharey=True,
            )
            axes_grid = np.asarray(axs, dtype=object)
            if axes_grid.ndim == 0:
                axes_grid = axes_grid.reshape(1, 1)
            elif axes_grid.ndim != 2:
                axes_grid = axes_grid.reshape(source_count, source_count)  # pragma: no cover
            entry_by_position = {
                (int(output_index), int(input_index)): (channel_data, pair_label)
                for output_index, input_index, channel_data, pair_label in typed_entries
            }
            for output_index in range(source_count):
                for input_index in range(source_count):
                    ax_i = axes_grid[output_index, input_index]
                    entry = entry_by_position.get((output_index, input_index))
                    if entry is not None:
                        channel_data, pair_label = entry
                        self.channel_plot(
                            bf.freqs,
                            channel_data,
                            ax_i,
                            title=pair_label,
                            ylabel=ylabel,
                            xlabel=xlabel,
                            alpha=alpha,
                            **plot_kwargs,
                        )
                    ax_i.set(**ax_set)
                    ax_i.set_xlabel(xlabel)
            fig.suptitle(title or bf.label or "Spectral Data")
            plt.tight_layout()
            notebook.show_figure(fig)
            return _return_axes_iterator(fig.axes)

        num_channels = bf.n_channels
        num_rows = int(np.ceil(np.sqrt(num_channels)))
        fig, axs = plt.subplots(
            num_rows,
            num_rows,
            figsize=(3 * num_rows, 3 * num_rows),
            sharex=True,
            sharey=True,
        )
        if isinstance(axs, np.ndarray):
            axes_list = axs.flatten().tolist()
        elif isinstance(axs, list):
            import itertools

            axes_list = list(itertools.chain.from_iterable(axs))
        else:
            axes_list = [axs]
        for ax_i, channel_data, ch_meta in zip(axes_list, data, bf.channels, strict=False):
            self.channel_plot(
                bf.freqs,
                channel_data,
                ax_i,
                title=ch_meta.label,
                ylabel=ylabel,
                xlabel=xlabel,
                alpha=alpha,
                **plot_kwargs,
            )
            ax_i.set(**ax_set)
            ax_i.set_xlabel(xlabel)
        fig.suptitle(title or bf.label or "Spectral Data")
        plt.tight_layout()
        notebook.show_figure(fig)
        return _return_axes_iterator(fig.axes)
Attributes
name = 'matrix' class-attribute instance-attribute
Functions
channel_plot(x, y, ax, label=None, alpha=1.0, **kwargs)
Source code in wandas/visualization/plotting.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def channel_plot(
    self,
    x: Any,
    y: Any,
    ax: Axes,
    label: PlotLabel = None,
    alpha: float = 1.0,
    **kwargs: Any,
) -> None:
    # Work on a local copy to avoid mutating caller-provided kwargs
    plot_kwargs = dict(kwargs)

    # Extract axes settings from kwargs copy
    title = plot_kwargs.pop("title", None)
    ylabel = plot_kwargs.pop("ylabel", None)
    xlabel = plot_kwargs.pop("xlabel", "Frequency [Hz]")

    if label is not None:
        plot_kwargs["label"] = label
    if alpha is not None and alpha != 1.0:
        plot_kwargs["alpha"] = alpha
    ax.plot(x, y, **plot_kwargs)
    ax.grid(True)
    if title is not None:
        ax.set_title(title)
    if ylabel is not None:
        ax.set_ylabel(ylabel)
    ax.set_xlabel(xlabel)
    if label is not None:
        ax.legend()
plot(bf, ax=None, title=None, overlay=False, **kwargs)
Source code in wandas/visualization/plotting.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
def plot(
    self,
    bf: SpectralFrame,
    ax: Axes | None = None,
    title: str | None = None,
    overlay: bool = False,
    **kwargs: Any,
) -> Axes | Iterator[Axes]:
    kwargs = kwargs or {}
    plt = _matplotlib_pyplot("matrix plot")
    axes_cls = _matplotlib_axes_type("matrix plot")
    line2d_cls = _matplotlib_line2d_type("matrix plot")
    is_aw = kwargs.pop("Aw", False)
    view = kwargs.pop("view", None)
    typed_entries = _typed_matrix_entries(bf, view=view, aw=is_aw)
    if typed_entries is not None:
        typed_ylabel = _typed_plot_ylabel(bf, view=view, aw=is_aw)
        if typed_ylabel is None:
            typed_values = _typed_frequency_values(bf, view=view, aw=is_aw)
            if typed_values is None:
                raise TypeError(f"{type(bf).__name__} exposes matrix entries without a frequency plotting contract")
            _, default_ylabel = typed_values
        else:
            default_ylabel = typed_ylabel
        ylabel = kwargs.pop("ylabel", default_ylabel)
    else:
        if view is not None:
            raise ValueError(
                "The 'view' argument is supported only by a typed quantity Frame; "
                "ordinary SpectralFrame plotting uses its amplitude level."
            )
        if is_aw:
            data = bf.dBA
            default_ylabel = "A-weighted amplitude level [dB re channel ref]"
        else:
            data = bf.dB
            default_ylabel = "Amplitude level [dB re channel ref]"
        data = _reshape_to_2d(data)
        ylabel = kwargs.pop("ylabel", default_ylabel)

    xlabel = kwargs.pop("xlabel", "Frequency [Hz]")
    alpha = kwargs.pop("alpha", 1)
    plot_kwargs = filter_kwargs(line2d_cls, kwargs, strict_mode=True)
    ax_set = filter_kwargs(axes_cls.set, kwargs, strict_mode=True)

    # If an Axes is provided, prefer drawing into it (treat as overlay)
    if ax is not None:
        overlay = True
    if overlay:
        created_figure = ax is None
        if ax is None:
            fig, ax = plt.subplots(1, 1, figsize=(6, 6))
        else:
            fig = ax.figure
        if ax is None:
            raise RuntimeError(  # pragma: no cover
                "Matplotlib did not provide an Axes for matrix plotting"
            )
        if typed_entries is None:
            self.channel_plot(
                bf.freqs,
                data.T,
                ax,  # Always Axes type here
                title=title or bf.label or "Spectral Data",
                ylabel=ylabel,
                xlabel=xlabel,
                alpha=alpha,
                **plot_kwargs,
            )
        else:
            for output_index, input_index, channel_data, pair_label in typed_entries:
                del output_index, input_index
                self.channel_plot(
                    bf.freqs,
                    channel_data,
                    ax,
                    label=pair_label,
                    title=title or bf.label or "Spectral Data",
                    ylabel=ylabel,
                    xlabel=xlabel,
                    alpha=alpha,
                    **plot_kwargs,
                )
        ax.set(**ax_set)
        if fig is not None:
            fig.suptitle(title or bf.label or "Spectral Data")
        if ax.figure != fig:  # Only show if we created the figure
            plt.tight_layout()
            notebook.show_figure(cast("Figure", fig))
        elif created_figure:
            notebook.display_new_figure(cast("Figure", fig))
        return cast("Axes", ax)

    if typed_entries is not None:
        source_count = int(getattr(bf, "n_source_channels", 0))
        if source_count <= 0:
            raise ValueError("A typed pairwise matrix requires at least one source channel")
        fig, axs = plt.subplots(
            source_count,
            source_count,
            figsize=(3 * source_count, 3 * source_count),
            sharex=True,
            sharey=True,
        )
        axes_grid = np.asarray(axs, dtype=object)
        if axes_grid.ndim == 0:
            axes_grid = axes_grid.reshape(1, 1)
        elif axes_grid.ndim != 2:
            axes_grid = axes_grid.reshape(source_count, source_count)  # pragma: no cover
        entry_by_position = {
            (int(output_index), int(input_index)): (channel_data, pair_label)
            for output_index, input_index, channel_data, pair_label in typed_entries
        }
        for output_index in range(source_count):
            for input_index in range(source_count):
                ax_i = axes_grid[output_index, input_index]
                entry = entry_by_position.get((output_index, input_index))
                if entry is not None:
                    channel_data, pair_label = entry
                    self.channel_plot(
                        bf.freqs,
                        channel_data,
                        ax_i,
                        title=pair_label,
                        ylabel=ylabel,
                        xlabel=xlabel,
                        alpha=alpha,
                        **plot_kwargs,
                    )
                ax_i.set(**ax_set)
                ax_i.set_xlabel(xlabel)
        fig.suptitle(title or bf.label or "Spectral Data")
        plt.tight_layout()
        notebook.show_figure(fig)
        return _return_axes_iterator(fig.axes)

    num_channels = bf.n_channels
    num_rows = int(np.ceil(np.sqrt(num_channels)))
    fig, axs = plt.subplots(
        num_rows,
        num_rows,
        figsize=(3 * num_rows, 3 * num_rows),
        sharex=True,
        sharey=True,
    )
    if isinstance(axs, np.ndarray):
        axes_list = axs.flatten().tolist()
    elif isinstance(axs, list):
        import itertools

        axes_list = list(itertools.chain.from_iterable(axs))
    else:
        axes_list = [axs]
    for ax_i, channel_data, ch_meta in zip(axes_list, data, bf.channels, strict=False):
        self.channel_plot(
            bf.freqs,
            channel_data,
            ax_i,
            title=ch_meta.label,
            ylabel=ylabel,
            xlabel=xlabel,
            alpha=alpha,
            **plot_kwargs,
        )
        ax_i.set(**ax_set)
        ax_i.set_xlabel(xlabel)
    fig.suptitle(title or bf.label or "Spectral Data")
    plt.tight_layout()
    notebook.show_figure(fig)
    return _return_axes_iterator(fig.axes)

Functions

register_plot_strategy(strategy_cls)

Register a new plot strategy from a class

Source code in wandas/visualization/plotting.py
1198
1199
1200
1201
1202
1203
1204
def register_plot_strategy(strategy_cls: type) -> None:
    """Register a new plot strategy from a class"""
    if not issubclass(strategy_cls, PlotStrategy):
        raise TypeError("Strategy class must inherit from PlotStrategy.")
    if inspect.isabstract(strategy_cls):
        raise TypeError("Cannot register abstract PlotStrategy class.")
    _plot_strategies[strategy_cls.name] = strategy_cls

get_plot_strategy(name)

Get plot strategy by name

Source code in wandas/visualization/plotting.py
1213
1214
1215
1216
1217
def get_plot_strategy(name: str) -> type[PlotStrategy[Any]]:
    """Get plot strategy by name"""
    if name not in _plot_strategies:
        raise ValueError(f"Unknown plot type: {name}")
    return _plot_strategies[name]

create_operation(name, **params)

Create operation instance from operation name and parameters

Source code in wandas/visualization/plotting.py
1220
1221
1222
1223
def create_operation(name: str, **params: Any) -> PlotStrategy[Any]:
    """Create operation instance from operation name and parameters"""
    operation_class = get_plot_strategy(name)
    return operation_class(**params)

wandas.visualization.describe

Composite static visualization workflow behind ChannelFrame.describe.

Attributes

logger = logging.getLogger(__name__) module-attribute

__all__ = ['describe_frame'] module-attribute

Classes

Functions

describe_frame(frame, normalize=True, is_close=True, *, fmin=0, fmax=None, cmap='jet', vmin=None, vmax=None, xlim=None, ylim=None, Aw=False, waveform=None, spectral=None, image_save=None, **kwargs)

Create, save, optionally display, and close per-channel summaries.

Source code in wandas/visualization/describe.py
 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
def describe_frame(
    frame: ChannelFrame,
    normalize: bool = True,
    is_close: bool = True,
    *,
    fmin: float = 0,
    fmax: float | None = None,
    cmap: str = "jet",
    vmin: float | None = None,
    vmax: float | None = None,
    xlim: tuple[float, float] | None = None,
    ylim: tuple[float, float] | None = None,
    Aw: bool = False,  # noqa: N803
    waveform: dict[str, Any] | None = None,
    spectral: dict[str, Any] | None = None,
    image_save: str | Path | None = None,
    **kwargs: Any,
) -> list[Figure] | None:
    """Create, save, optionally display, and close per-channel summaries."""
    plot_kwargs: dict[str, Any] = {
        "fmin": fmin,
        "fmax": fmax,
        "cmap": cmap,
        "vmin": vmin,
        "vmax": vmax,
        "xlim": xlim,
        "ylim": ylim,
        "Aw": Aw,
        "waveform": waveform or {},
        "spectral": spectral or {},
    }
    plot_kwargs.update(kwargs)
    _apply_deprecated_describe_kwargs(plot_kwargs)

    axes_cls = require_matplotlib_axes_type("describe")
    pyplot = require_matplotlib_pyplot("describe")
    display_session: notebook.NotebookDisplay | None = None
    pyscript_target: str | None = None
    show_with_pyplot = False
    if image_save is None and is_close:
        # PyScript renders through its own display(); its target wins over
        # notebook detection because neither IPython nor pyplot reaches the page.
        pyscript_target = notebook.pyscript_display_target()
        if pyscript_target is None and notebook.in_notebook_frontend():
            try:
                display_session = notebook.resolve_notebook_display("describe")
            except ImportError:
                logger.info(
                    "IPython is not installed; showing describe() figures with matplotlib.pyplot.show() "
                    'without audio playback. Install it with: pip install "wandas[marimo]"'
                )
                show_with_pyplot = True
        elif pyscript_target is None:
            # Outside a notebook, IPython.display only prints object reprs, so
            # the figures go through the active Matplotlib backend instead and
            # notebook audio playback is skipped.
            show_with_pyplot = True
    figures: list[Figure] = []
    shown_figures: list[Figure] = []
    # Each channel summary materializes the waveform, STFT, and Welch views
    # (plus audio in notebooks); compute the source once so a lazy file-backed
    # frame is not decoded again for every view of every channel. persist()
    # keeps the channel-wise chunks, so in-memory samples are not copied.
    frame = frame._create_new_instance(frame._data.persist())

    completed = False
    try:
        for channel_index, channel in enumerate(frame):
            plotted = channel.plot("describe", title=f"{channel.label} {channel.labels[0]}", **plot_kwargs)
            if isinstance(plotted, axes_cls):
                axes = plotted
            elif isinstance(plotted, Iterator):
                axes = cast("Axes", next(plotted))
            else:
                raise TypeError(f"Unexpected type for plot result: {type(plotted)}. Expected Axes or Iterator[Axes].")
            figure = cast("Figure | None", getattr(axes, "figure", None))
            if figure is None:
                continue

            try:
                if not is_close:
                    figures.append(figure)
                if image_save is not None:
                    _save_figure(figure, image_save, channel=channel_index, channel_count=frame.n_channels)
                if pyscript_target is not None:
                    notebook.display_in_pyscript(
                        figure,
                        pyscript_target,
                        audio=channel.data,
                        sampling_rate=channel.sampling_rate,
                        normalize=normalize,
                    )
                if display_session is not None:
                    notebook.display_figure_and_audio(
                        display_session,
                        figure,
                        channel.data,
                        sampling_rate=channel.sampling_rate,
                        normalize=normalize,
                    )
            finally:
                if show_with_pyplot:
                    shown_figures.append(figure)
                elif is_close:
                    figure.clf()
                    pyplot.close(figure)
        completed = True
    finally:
        # Figures held for pyplot.show() are released even when a later
        # channel fails before the single show call. In Matplotlib's
        # interactive mode show() returns immediately, so the figures stay
        # open for the user instead of being closed right after drawing.
        keep_open = False
        try:
            if completed and shown_figures:
                keep_open = pyplot.isinteractive()
                pyplot.show()
        finally:
            if not keep_open:
                for figure in shown_figures:
                    figure.clf()
                    pyplot.close(figure)

    return None if is_close else figures

wandas.visualization.notebook

Optional notebook presentation helpers for static Frame descriptions.

Attributes

__all__ = ['NotebookDisplay', 'display_figure_and_audio', 'display_in_pyscript', 'display_new_figure', 'in_notebook_frontend', 'pyscript_display_target', 'resolve_notebook_display', 'show_figure'] module-attribute

Classes

NotebookDisplay dataclass

Resolved optional IPython display functions for one presentation call.

Source code in wandas/visualization/notebook.py
21
22
23
24
25
26
@dataclass(frozen=True)
class NotebookDisplay:
    """Resolved optional IPython display functions for one presentation call."""

    display: Callable[..., Any]
    audio: Callable[..., Any]
Attributes
display instance-attribute
audio instance-attribute
Functions
__init__(display, audio)

Functions

in_notebook_frontend()

Return whether rich output reaches a notebook front end.

True inside marimo or an IPython kernel (Jupyter, VS Code, Colab). A plain script or the terminal IPython shell has nowhere to render IPython.display output, so it gets False even when IPython is installed. Only modules the session has already imported are inspected.

Source code in wandas/visualization/notebook.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def in_notebook_frontend() -> bool:
    """Return whether rich output reaches a notebook front end.

    True inside marimo or an IPython kernel (Jupyter, VS Code, Colab). A plain
    script or the terminal IPython shell has nowhere to render
    ``IPython.display`` output, so it gets False even when IPython is
    installed. Only modules the session has already imported are inspected.
    """
    marimo = sys.modules.get("marimo")
    if marimo is not None and marimo.running_in_notebook():
        return True
    ipython = sys.modules.get("IPython")
    shell = ipython.get_ipython() if ipython is not None else None
    if shell is None:
        return False
    terminal = sys.modules.get("IPython.terminal.interactiveshell")
    return terminal is None or not isinstance(shell, terminal.TerminalInteractiveShell)

pyscript_display_target()

Return the PyScript element id that pyscript.display writes to.

None outside PyScript, and inside PyScript when the running code has no output element (current_target() is empty, as in py-editor). Only an already imported pyscript module is inspected.

Source code in wandas/visualization/notebook.py
48
49
50
51
52
53
54
55
56
57
58
59
60
def pyscript_display_target() -> str | None:
    """Return the PyScript element id that ``pyscript.display`` writes to.

    None outside PyScript, and inside PyScript when the running code has no
    output element (``current_target()`` is empty, as in ``py-editor``). Only
    an already imported ``pyscript`` module is inspected.
    """
    pyscript = sys.modules.get("pyscript")
    current_target = getattr(pyscript, "current_target", None)
    if not callable(current_target):
        return None
    target = current_target()
    return target if isinstance(target, str) and target else None

display_in_pyscript(figure, target, *, audio=None, sampling_rate=None, normalize=True)

Append a Figure, and optionally an audio player, to a PyScript element.

Source code in wandas/visualization/notebook.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def display_in_pyscript(
    figure: Figure,
    target: str,
    *,
    audio: Any = None,
    sampling_rate: float | None = None,
    normalize: bool = True,
) -> None:
    """Append a Figure, and optionally an audio player, to a PyScript element."""
    pyscript = sys.modules["pyscript"]
    pyscript.display(figure, target=target, append=True)
    if audio is not None and sampling_rate is not None:
        source = _wav_data_uri(audio, sampling_rate=sampling_rate, normalize=normalize)
        pyscript.display(pyscript.HTML(f'<audio controls src="{source}"></audio>'), target=target, append=True)

display_new_figure(figure)

Display and close a Figure a plot call created, when PyScript has a target.

PyScript has no end-of-cell figure rendering, so a plot that returns its Axes without pyplot.show() would otherwise never reach the page. Returns whether the Figure was displayed.

Source code in wandas/visualization/notebook.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def display_new_figure(figure: Figure) -> bool:
    """Display and close a Figure a plot call created, when PyScript has a target.

    PyScript has no end-of-cell figure rendering, so a plot that returns its
    Axes without ``pyplot.show()`` would otherwise never reach the page.
    Returns whether the Figure was displayed.
    """
    target = pyscript_display_target()
    if target is None:
        return False
    try:
        display_in_pyscript(figure, target)
    finally:
        require_matplotlib_pyplot("plot").close(figure)
    return True

show_figure(figure)

Show a Figure a plot call created: in PyScript when it has a target, else with pyplot.

Source code in wandas/visualization/notebook.py
115
116
117
118
def show_figure(figure: Figure) -> None:
    """Show a Figure a plot call created: in PyScript when it has a target, else with pyplot."""
    if not display_new_figure(figure):
        require_matplotlib_pyplot("plot").show()

resolve_notebook_display(feature='describe')

Resolve IPython display support before expensive plot generation.

Source code in wandas/visualization/notebook.py
121
122
123
124
def resolve_notebook_display(feature: str = "describe") -> NotebookDisplay:
    """Resolve IPython display support before expensive plot generation."""
    display, audio = require_ipython_display(feature)
    return NotebookDisplay(display=display, audio=audio)

display_figure_and_audio(session, figure, data, *, sampling_rate, normalize)

Present one static Figure followed by its matching audio channel.

Source code in wandas/visualization/notebook.py
127
128
129
130
131
132
133
134
135
136
137
def display_figure_and_audio(
    session: NotebookDisplay,
    figure: Figure,
    data: Any,
    *,
    sampling_rate: float,
    normalize: bool,
) -> None:
    """Present one static Figure followed by its matching audio channel."""
    session.display(figure)
    session.display(session.audio(data, rate=sampling_rate, normalize=normalize))