Skip to content

Visualizations & Plotting

The stride.plotting subpackage provides headless visualization functions for data streams, class distributions, and feature manifolds.


Overview

All visualization utilities generate and return matplotlib.figure.Figure instances without invoking plt.show(). This guarantees non-blocking execution across headless CI servers, automated scripts, and Streamlit dashboard containers (st.pyplot(fig)).

from stride.plotting import (
    visualize_data_stream,
    plot_class_distribution,
    plot_feature_space,
    plot_feature_target_relationship,
    plot_class_share_over_time,
    plot_feature_over_time,
)

Key Components

Function Return Type Description
visualize_data_stream Figure Multi-panel stream trajectory overview plotting feature values and target labels across the time index.
plot_class_distribution Figure Class balance evolution chart displaying categorical target proportions across sliding windows.
plot_feature_space Figure 2D scatter visualization of feature coordinates color-coded by class labels.
plot_feature_target_relationship Figure Density and violin plots visualizing feature-target relationships pre- and post-drift.
plot_class_share_over_time Figure Stacked area chart of the class shares along the whole stream, with known change points marked.
plot_feature_over_time Figure Class-wise mean of one feature along the whole stream (one panel per class) with the mean of every segment between change points.

API Specification

stride.plotting

Data stream and feature distribution plotting utilities.

plot_class_distribution

plot_class_distribution(
    class_dist_before,
    class_dist_after,
    class_colors,
    title="Class Distribution",
)

Create a figure showing class distribution before and after a window.

Parameters:

Name Type Description Default
class_dist_before

{class_id: proportion} for the before window.

required
class_dist_after

{class_id: proportion} for the after window.

required
class_colors

Mapping {class_id: color_string}.

required
title

Figure title.

'Class Distribution'

Returns:

Type Description
Figure

The generated Matplotlib Figure.

Source code in src/stride/plotting/stream.py
def plot_class_distribution(class_dist_before, class_dist_after, class_colors, title="Class Distribution") -> Figure:
    """Create a figure showing class distribution before and after a window.

    Args:
        class_dist_before: `{class_id: proportion}` for the *before* window.
        class_dist_after: `{class_id: proportion}` for the *after* window.
        class_colors: Mapping `{class_id: color_string}`.
        title: Figure title.

    Returns:
        The generated Matplotlib Figure.
    """
    _ensure_matplotlib()
    fig, (ax_before, ax_after) = plt.subplots(1, 2, figsize=(12, 6))
    if title:
        fig.suptitle(title, fontsize=16, fontweight="bold", y=1.0)

    classes = sorted(class_colors.keys())
    labels = [f"Class {c}" for c in classes]
    colors = [class_colors[c] for c in classes]

    ax_before.bar(labels, [class_dist_before.get(c, 0) for c in classes], color=colors, alpha=0.7, edgecolor="black")
    ax_before.set_ylabel("Proportion")
    ax_before.set_title("Before")
    ax_before.set_ylim([0, 1])
    ax_before.grid(True, alpha=0.3, axis="y")

    ax_after.bar(labels, [class_dist_after.get(c, 0) for c in classes], color=colors, alpha=0.7, edgecolor="black")
    ax_after.set_ylabel("Proportion")
    ax_after.set_title("After")
    ax_after.set_ylim([0, 1])
    ax_after.grid(True, alpha=0.3, axis="y")

    plt.tight_layout()
    fig.subplots_adjust(top=0.88)
    return fig

plot_class_share_over_time

plot_class_share_over_time(
    y,
    change_points=None,
    n_bins=100,
    class_colors=None,
    segment_labels=None,
    title="Class share along the stream",
    legend=True,
    ax=None,
)

Plot the class proportions along a stream as a stacked area chart.

The stream is cut into n_bins consecutive bins of equal length and the share of every class is computed per bin. It shows prior drift \(P(Y)\), classes that arrive in bursts and periods in which a class is absent.

Parameters:

Name Type Description Default
y Sequence | ndarray | Series

Class labels in stream order.

required
change_points Sequence[int] | None

Positions (row indices) of known changes, drawn as vertical rules.

None
n_bins int

Number of consecutive bins the stream is cut into.

100
class_colors Mapping | None

Mapping {class: color}; a default palette is used when omitted.

None
segment_labels Sequence[str] | None

Names of the segments between the change points, written above the axes. Requires one name more than there are change points.

None
title str | None

Axes title.

'Class share along the stream'
legend bool

Whether to draw the class legend below the axes.

True
ax Axes | None

Axes to draw on; a new figure is created when omitted.

None

Returns:

Type Description
Figure

The Matplotlib Figure holding the chart.

Raises:

Type Description
ValueError

If the number of segment_labels does not match the number of segments.

Source code in src/stride/plotting/stream.py
def plot_class_share_over_time(
    y: Sequence | np.ndarray | pd.Series,
    change_points: Sequence[int] | None = None,
    n_bins: int = 100,
    class_colors: Mapping | None = None,
    segment_labels: Sequence[str] | None = None,
    title: str | None = "Class share along the stream",
    legend: bool = True,
    ax: Axes | None = None,
) -> Figure:
    """Plot the class proportions along a stream as a stacked area chart.

    The stream is cut into `n_bins` consecutive bins of equal length and the share of
    every class is computed per bin. It shows prior drift $P(Y)$, classes that arrive
    in bursts and periods in which a class is absent.

    Args:
        y: Class labels in stream order.
        change_points: Positions (row indices) of known changes, drawn as vertical rules.
        n_bins: Number of consecutive bins the stream is cut into.
        class_colors: Mapping `{class: color}`; a default palette is used when omitted.
        segment_labels: Names of the segments between the change points, written above
            the axes. Requires one name more than there are change points.
        title: Axes title.
        legend: Whether to draw the class legend below the axes.
        ax: Axes to draw on; a new figure is created when omitted.

    Returns:
        The Matplotlib Figure holding the chart.

    Raises:
        ValueError: If the number of `segment_labels` does not match the number of segments.
    """
    _ensure_matplotlib()
    labels = pd.Series(np.asarray(y))
    classes = sorted(labels.unique())
    colors = class_colors or _default_class_colors(classes)

    edges = np.linspace(0, len(labels), n_bins + 1)
    bins = pd.cut(np.arange(len(labels)), edges, right=False, labels=False)
    share = pd.crosstab(bins, labels.values, normalize="index").reindex(index=range(n_bins), columns=classes, fill_value=0.0)

    if ax is None:
        _, ax = plt.subplots(figsize=(12, 3))
    ax.stackplot(
        (edges[:-1] + edges[1:]) / 2,
        share.T.values,
        colors=[colors[c] for c in classes],
        labels=[str(c) for c in classes],
        edgecolor="white",
        linewidth=0.3,
    )
    _mark_change_points(ax, len(labels), change_points, segment_labels)
    ax.set_ylim(0, 1)
    ax.set_xlabel("Position in the stream")
    ax.set_ylabel("Class share")
    if title:
        ax.set_title(title, pad=16 if segment_labels is not None else None)
    if legend:
        ax.legend(ncol=min(len(classes), 6), loc="upper center", bbox_to_anchor=(0.5, -0.25), fontsize=8, frameon=False)
    return ax.figure

plot_feature_over_time

plot_feature_over_time(
    values,
    y,
    change_points=None,
    n_bins=100,
    min_count=15,
    class_colors=None,
    segment_labels=None,
    title=None,
    figsize=None,
)

Plot the class-wise mean of one feature along a stream, one panel per class.

The stream is cut into n_bins consecutive bins; the coloured line is the mean of the feature per bin and class, and the black segments are the class-wise mean of every segment between two change points. A level shift at a change point is drift of \(P(X \mid Y)\); movement inside a segment is drift that was not annotated.

Parameters:

Name Type Description Default
values Sequence | ndarray | Series

Values of one feature in stream order. The name of a Series is used as the feature name.

required
y Sequence | ndarray | Series

Class labels in stream order.

required
change_points Sequence[int] | None

Positions (row indices) of known changes, drawn as vertical rules.

None
n_bins int

Number of consecutive bins the stream is cut into.

100
min_count int

Bins with fewer samples of a class are left out of the line of that class.

15
class_colors Mapping | None

Mapping {class: color}; a default palette is used when omitted.

None
segment_labels Sequence[str] | None

Names of the segments between the change points, written above the first panel.

None
title str | None

Figure title; by default it names the feature.

None
figsize tuple[float, float] | None

Figure size; by default 12 inches wide and 1.4 inches per class.

None

Returns:

Type Description
Figure

The Matplotlib Figure with one panel per class.

Raises:

Type Description
ValueError

If values and y differ in length, or the number of segment_labels does not match the number of segments.

Source code in src/stride/plotting/stream.py
def plot_feature_over_time(
    values: Sequence | np.ndarray | pd.Series,
    y: Sequence | np.ndarray | pd.Series,
    change_points: Sequence[int] | None = None,
    n_bins: int = 100,
    min_count: int = 15,
    class_colors: Mapping | None = None,
    segment_labels: Sequence[str] | None = None,
    title: str | None = None,
    figsize: tuple[float, float] | None = None,
) -> Figure:
    """Plot the class-wise mean of one feature along a stream, one panel per class.

    The stream is cut into `n_bins` consecutive bins; the coloured line is the mean of
    the feature per bin and class, and the black segments are the class-wise mean of
    every segment between two change points. A level shift at a change point is drift
    of $P(X \\mid Y)$; movement inside a segment is drift that was not annotated.

    Args:
        values: Values of one feature in stream order. The name of a Series is used as the feature name.
        y: Class labels in stream order.
        change_points: Positions (row indices) of known changes, drawn as vertical rules.
        n_bins: Number of consecutive bins the stream is cut into.
        min_count: Bins with fewer samples of a class are left out of the line of that class.
        class_colors: Mapping `{class: color}`; a default palette is used when omitted.
        segment_labels: Names of the segments between the change points, written above the first panel.
        title: Figure title; by default it names the feature.
        figsize: Figure size; by default 12 inches wide and 1.4 inches per class.

    Returns:
        The Matplotlib Figure with one panel per class.

    Raises:
        ValueError: If `values` and `y` differ in length, or the number of `segment_labels`
            does not match the number of segments.
    """
    _ensure_matplotlib()
    feature = str(getattr(values, "name", None) or "feature")
    if len(values) != len(y):
        raise ValueError("`values` and `y` must have the same length.")
    frame = pd.DataFrame({"value": np.asarray(values, dtype=float), "label": np.asarray(y)})
    n = len(frame)
    classes = sorted(frame["label"].unique())
    colors = class_colors or _default_class_colors(classes)

    edges = np.linspace(0, n, n_bins + 1)
    mid = (edges[:-1] + edges[1:]) / 2
    frame["bin"] = pd.cut(np.arange(n), edges, right=False, labels=False)
    bounds = [0, *(change_points or []), n]
    frame["segment"] = np.searchsorted(bounds[1:-1], np.arange(n), side="right")
    binned = frame.groupby(["bin", "label"])["value"].agg(["mean", "count"])
    segment_mean = frame.groupby(["segment", "label"])["value"].mean()

    fig, axes = plt.subplots(len(classes), 1, figsize=figsize or (12, 1.4 * len(classes) + 0.8), sharex=True, squeeze=False)
    for i, (ax, cl) in enumerate(zip(axes[:, 0], classes)):
        stats = binned.xs(cl, level="label").reindex(range(n_bins))
        ax.plot(mid, stats["mean"].where(stats["count"] >= min_count), color=colors[cl], linewidth=1.1)
        for s, (lo, hi) in enumerate(zip(bounds[:-1], bounds[1:])):
            if (s, cl) in segment_mean.index:
                ax.hlines(segment_mean[s, cl], lo, hi, color="black", linewidth=1.5)
        _mark_change_points(ax, n, change_points, segment_labels if i == 0 else None)
        ax.set_ylabel(str(cl), fontsize=8)
        ax.grid(axis="y", alpha=0.3)
    axes[-1, 0].set_xlabel("Position in the stream")
    fig.suptitle(title or f"Class-wise mean of {feature} along the stream (line: bins, black: segment mean)", fontsize=11)
    fig.tight_layout()
    return fig

plot_feature_space

plot_feature_space(
    n_features,
    feature_names,
    X_before,
    X_after,
    y_before,
    y_after,
    class_colors,
    title="Feature Space",
)

Create a figure showing the feature space for two windows (1D, 2D, or PCA).

Parameters:

Name Type Description Default
n_features

Number of features.

required
feature_names

Feature names.

required
X_before

Feature matrix for the before window.

required
X_after

Feature matrix for the after window.

required
y_before

Class labels for the before window.

required
y_after

Class labels for the after window.

required
class_colors

Mapping {class_id: color_string}.

required
title

Figure title.

'Feature Space'

Returns:

Type Description
Figure

The generated Matplotlib Figure.

Source code in src/stride/plotting/stream.py
def plot_feature_space(
    n_features, feature_names, X_before, X_after, y_before, y_after, class_colors, title="Feature Space"
) -> Figure:
    """Create a figure showing the feature space for two windows (1D, 2D, or PCA).

    Args:
        n_features: Number of features.
        feature_names: Feature names.
        X_before: Feature matrix for the *before* window.
        X_after: Feature matrix for the *after* window.
        y_before: Class labels for the *before* window.
        y_after: Class labels for the *after* window.
        class_colors: Mapping `{class_id: color_string}`.
        title: Figure title.

    Returns:
        The generated Matplotlib Figure.
    """
    _ensure_matplotlib()
    fig, (ax_before, ax_after) = plt.subplots(1, 2, figsize=(14, 7))
    fs_title_suffix = ""

    unique_classes = sorted(class_colors.keys())

    if n_features == 1:
        for cls in unique_classes:
            ax_before.hist(X_before[y_before == cls], bins=30, alpha=0.5, label=f"Class {cls}", color=class_colors[cls])
            ax_after.hist(X_after[y_after == cls], bins=30, alpha=0.5, label=f"Class {cls}", color=class_colors[cls])
        ax_before.set_xlabel(feature_names[0])
        ax_after.set_xlabel(feature_names[0])
        ax_before.set_ylabel("Frequency")
        ax_after.set_ylabel("Frequency")

    elif n_features == 2:
        for cls in unique_classes:
            ax_before.scatter(
                X_before[y_before == cls, 0],
                X_before[y_before == cls, 1],
                alpha=0.5,
                s=20,
                label=f"Class {cls}",
                color=class_colors[cls],
            )
            ax_after.scatter(
                X_after[y_after == cls, 0],
                X_after[y_after == cls, 1],
                alpha=0.5,
                s=20,
                label=f"Class {cls}",
                color=class_colors[cls],
            )
        ax_before.set_xlabel(feature_names[0])
        ax_before.set_ylabel(feature_names[1])
        ax_after.set_xlabel(feature_names[0])
        ax_after.set_ylabel(feature_names[1])

    else:
        pca = PCA(n_components=2, random_state=42)
        X_combined = np.concatenate([X_before, X_after])
        X_2d = pca.fit_transform(X_combined)

        X_2d_before = X_2d[: len(X_before)]
        X_2d_after = X_2d[len(X_before) :]

        for cls in unique_classes:
            ax_before.scatter(
                X_2d_before[y_before == cls, 0],
                X_2d_before[y_before == cls, 1],
                alpha=0.5,
                s=20,
                label=f"Class {cls}",
                color=class_colors[cls],
            )
            ax_after.scatter(
                X_2d_after[y_after == cls, 0],
                X_2d_after[y_after == cls, 1],
                alpha=0.5,
                s=20,
                label=f"Class {cls}",
                color=class_colors[cls],
            )
        ax_before.set_xlabel("Principal Component 1")
        ax_before.set_ylabel("Principal Component 2")
        ax_after.set_xlabel("Principal Component 1")
        ax_after.set_ylabel("Principal Component 2")
        fs_title_suffix = " (PCA)"

    ax_before.set_title("Before")
    ax_before.legend()
    ax_before.grid(True, alpha=0.3)

    ax_after.set_title("After")
    ax_after.legend()
    ax_after.grid(True, alpha=0.3)

    if title:
        fig.suptitle(title + fs_title_suffix, fontsize=16, fontweight="bold", y=1.0)

    plt.tight_layout()
    fig.subplots_adjust(top=0.88)
    return fig

plot_feature_target_relationship

plot_feature_target_relationship(
    X,
    n_features,
    feature_names,
    X_before,
    X_after,
    y_before,
    y_after,
    class_colors,
    title="Feature vs Target Relationship",
    viz_type="violin",
)

Create a figure showing feature distributions grouped by class and window.

Each subplot corresponds to one feature. Within each subplot, distributions are stacked horizontally — one pair (Before / After) per class.

Parameters:

Name Type Description Default
X

Full feature matrix (used only for shape information).

required
n_features

Number of features.

required
feature_names

Feature names.

required
X_before

Feature matrix for the before window.

required
X_after

Feature matrix for the after window.

required
y_before

Class labels for the before window.

required
y_after

Class labels for the after window.

required
class_colors

Mapping {class_id: color_string}.

required
title

Figure title.

'Feature vs Target Relationship'
viz_type

Distribution plot type ("violin", "box", or "scatter").

'violin'

Returns:

Type Description
Figure

The generated Matplotlib Figure.

Source code in src/stride/plotting/stream.py
def plot_feature_target_relationship(
    X,
    n_features,
    feature_names,
    X_before,
    X_after,
    y_before,
    y_after,
    class_colors,
    title="Feature vs Target Relationship",
    viz_type="violin",
) -> Figure:
    """Create a figure showing feature distributions grouped by class and window.

    Each subplot corresponds to one feature. Within each subplot, distributions
    are stacked horizontally — one pair (Before / After) per class.

    Args:
        X: Full feature matrix (used only for shape information).
        n_features: Number of features.
        feature_names: Feature names.
        X_before: Feature matrix for the *before* window.
        X_after: Feature matrix for the *after* window.
        y_before: Class labels for the *before* window.
        y_after: Class labels for the *after* window.
        class_colors: Mapping `{class_id: color_string}`.
        title: Figure title.
        viz_type: Distribution plot type ("violin", "box", or "scatter").

    Returns:
        The generated Matplotlib Figure.
    """
    _ensure_matplotlib()
    unique_classes = sorted(np.unique(np.concatenate([y_before, y_after])))
    n_classes = len(unique_classes)

    fig, axes = plt.subplots(n_features, 1, figsize=(10, (1.5 * n_classes + 0.5) * n_features), squeeze=False)

    if title:
        fig.suptitle(title, fontsize=16, fontweight="bold", y=0.99)

    for i in range(n_features):
        ax = axes[i, 0]
        feat_name = feature_names[i]

        plot_data = []
        for idx, cls in enumerate(unique_classes):
            color = class_colors[cls]
            base_pos = idx * 2.5

            plot_data.append(
                {
                    "label": f"Class {cls}\n(Before)",
                    "values": X_before[y_before == cls, i],
                    "color": color,
                    "alpha": 0.3,
                    "position": base_pos,
                }
            )
            plot_data.append(
                {
                    "label": f"Class {cls}\n(After)",
                    "values": X_after[y_after == cls, i],
                    "color": color,
                    "alpha": 0.8,
                    "position": base_pos + 1,
                }
            )

        _plot_distribution_comparison(ax, viz_type, plot_data, feat_name)
        ax.set_title(f"{feat_name} Distributions", fontsize=12)

    plt.tight_layout()
    fig.subplots_adjust(top=0.94)
    return fig

visualize_data_stream

visualize_data_stream(
    X,
    y,
    window_before_start,
    window_after_start,
    window_length,
    feature_names,
    title_feat_target="Feature vs Target Relationship",
    title_class_dist="Class Distribution",
    title_feat_space="Feature Space",
    viz_type="violin",
)

Visualize the data stream for two specific windows.

Creates three separate figures:

  1. Feature-target relationships (violin / box / scatter per feature per class)
  2. Class distributions (bar chart before vs after)
  3. Feature space (1D histogram, 2D scatter, or PCA projection)

Parameters:

Name Type Description Default
X

Full feature matrix.

required
y

Class labels.

required
window_before_start

Start index (inclusive) of the before window.

required
window_after_start

Start index (inclusive) of the after window.

required
window_length

Number of samples in each window.

required
feature_names

Feature names.

required
title_feat_target

Title for the feature-target figure.

'Feature vs Target Relationship'
title_class_dist

Title for the class-distribution figure.

'Class Distribution'
title_feat_space

Title for the feature-space figure.

'Feature Space'
viz_type

Distribution plot type ("violin", "box", or "scatter").

'violin'

Returns:

Type Description
list[Figure]

List of three figures in the order described above.

Source code in src/stride/plotting/stream.py
def visualize_data_stream(
    X,
    y,
    window_before_start,
    window_after_start,
    window_length,
    feature_names,
    title_feat_target="Feature vs Target Relationship",
    title_class_dist="Class Distribution",
    title_feat_space="Feature Space",
    viz_type="violin",
) -> list[Figure]:
    """Visualize the data stream for two specific windows.

    Creates three separate figures:

    1. Feature-target relationships (violin / box / scatter per feature per class)
    2. Class distributions (bar chart before vs after)
    3. Feature space (1D histogram, 2D scatter, or PCA projection)

    Args:
        X: Full feature matrix.
        y: Class labels.
        window_before_start: Start index (inclusive) of the *before* window.
        window_after_start: Start index (inclusive) of the *after* window.
        window_length: Number of samples in each window.
        feature_names: Feature names.
        title_feat_target: Title for the feature-target figure.
        title_class_dist: Title for the class-distribution figure.
        title_feat_space: Title for the feature-space figure.
        viz_type: Distribution plot type ("violin", "box", or "scatter").

    Returns:
        List of three figures in the order described above.
    """
    _ensure_matplotlib()
    if isinstance(X, pd.DataFrame):
        X = X.values
    if isinstance(y, pd.Series):
        y = y.values

    X_before = X[window_before_start : window_before_start + window_length]
    y_before = y[window_before_start : window_before_start + window_length]
    X_after = X[window_after_start : window_after_start + window_length]
    y_after = y[window_after_start : window_after_start + window_length]

    n_features = X.shape[1]
    unique_classes = np.unique(np.concatenate([y_before, y_after]))

    class_dist_before = {cls: np.mean(y_before == cls) for cls in unique_classes}
    class_dist_after = {cls: np.mean(y_after == cls) for cls in unique_classes}

    class_colors = _default_class_colors(unique_classes)

    return [
        plot_feature_target_relationship(
            X,
            n_features,
            feature_names,
            X_before,
            X_after,
            y_before,
            y_after,
            class_colors,
            title=title_feat_target,
            viz_type=viz_type,
        ),
        plot_class_distribution(class_dist_before, class_dist_after, class_colors, title=title_class_dist),
        plot_feature_space(
            n_features, feature_names, X_before, X_after, y_before, y_after, class_colors, title=title_feat_space
        ),
    ]