Skip to content

cds2.viz

Matplotlib plotting helpers.

Matplotlib plotting helpers for common scientific charts.

plot_series(data, title='', xlabel='', ylabel='', save=None)

Line plot of one or more series; a 2-D input plots each row.

Source code in src/cds2/viz.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def plot_series(
    data: object,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "",
    save: str | Path | None = None,
) -> Figure:
    """Line plot of one or more series; a 2-D input plots each row."""
    values = np.asarray(data, dtype=float)
    fig, ax = plt.subplots()
    if values.ndim == 1:
        ax.plot(values)
    else:
        for row in values:
            ax.plot(row)
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_histogram(data, bins=30, title='', xlabel='', ylabel='frequency', save=None)

Histogram of a sample.

Source code in src/cds2/viz.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def plot_histogram(
    data: object,
    bins: int = 30,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "frequency",
    save: str | Path | None = None,
) -> Figure:
    """Histogram of a sample."""
    values = np.asarray(data, dtype=float).ravel()
    fig, ax = plt.subplots()
    ax.hist(values, bins=bins, edgecolor="black", linewidth=0.4)
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_scatter(x, y, title='', xlabel='', ylabel='', save=None)

Scatter plot of paired samples.

Source code in src/cds2/viz.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def plot_scatter(
    x: object,
    y: object,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "",
    save: str | Path | None = None,
) -> Figure:
    """Scatter plot of paired samples."""
    fig, ax = plt.subplots()
    ax.scatter(np.asarray(x), np.asarray(y), s=18, alpha=0.8)
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_heatmap(matrix, cmap='viridis', colorbar=True, title='', xlabel='', ylabel='', save=None)

Heatmap of a 2-D matrix.

Source code in src/cds2/viz.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def plot_heatmap(
    matrix: object,
    cmap: str = "viridis",
    colorbar: bool = True,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "",
    save: str | Path | None = None,
) -> Figure:
    """Heatmap of a 2-D matrix."""
    values = np.asarray(matrix, dtype=float)
    fig, ax = plt.subplots()
    image = ax.imshow(values, aspect="auto", cmap=cmap)
    if colorbar:
        fig.colorbar(image, ax=ax)
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_spectrum(x, fs, title='Power spectrum', xlabel='frequency (Hz)', ylabel='PSD', save=None)

Log-scale power spectral density of a sampled signal.

Source code in src/cds2/viz.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def plot_spectrum(
    x: object,
    fs: float,
    title: str = "Power spectrum",
    xlabel: str = "frequency (Hz)",
    ylabel: str = "PSD",
    save: str | Path | None = None,
) -> Figure:
    """Log-scale power spectral density of a sampled signal."""
    from .signals import power_spectrum

    spectrum = power_spectrum(x, fs)
    keep = spectrum.frequencies > 0
    fig, ax = plt.subplots()
    ax.semilogy(spectrum.frequencies[keep], spectrum.power[keep])
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_regression(x, y, degree=1, points=200, title='Regression fit', xlabel='', ylabel='', save=None)

Scatter plot with a least-squares polynomial overlay.

Source code in src/cds2/viz.py
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
def plot_regression(
    x: object,
    y: object,
    degree: int = 1,
    points: int = 200,
    title: str = "Regression fit",
    xlabel: str = "",
    ylabel: str = "",
    save: str | Path | None = None,
) -> Figure:
    """Scatter plot with a least-squares polynomial overlay."""
    x_values = np.asarray(x, dtype=float).ravel()
    y_values = np.asarray(y, dtype=float).ravel()
    coefficients = np.polyfit(x_values, y_values, degree)
    grid = np.linspace(float(x_values.min()), float(x_values.max()), points)
    fig, ax = plt.subplots()
    ax.scatter(x_values, y_values, s=18, alpha=0.8, label="data")
    ax.plot(
        grid,
        np.polyval(coefficients, grid),
        color="crimson",
        linewidth=2,
        label=f"degree {degree} fit",
    )
    ax.legend(loc="best")
    _decorate(ax, title, xlabel, ylabel)
    if save is not None:
        save_figure(fig, save)
    return fig

plot_confusion_matrix(matrix, labels=None, title='Confusion matrix', save=None)

Annotated confusion-matrix heatmap.

Source code in src/cds2/viz.py
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
def plot_confusion_matrix(
    matrix: object,
    labels: list[str] | None = None,
    title: str = "Confusion matrix",
    save: str | Path | None = None,
) -> Figure:
    """Annotated confusion-matrix heatmap."""
    values = np.asarray(matrix)
    n_classes = values.shape[0]
    names = labels if labels is not None else [str(i) for i in range(n_classes)]
    fig, ax = plt.subplots()
    image = ax.imshow(values, cmap="Blues")
    fig.colorbar(image, ax=ax)
    threshold = float(values.max()) / 2.0 if values.size else 0.0
    for i in range(n_classes):
        for j in range(n_classes):
            color = "white" if values[i, j] > threshold else "black"
            ax.text(j, i, str(values[i, j]), ha="center", va="center", color=color)
    ticks = list(range(n_classes))
    ax.set_xticks(ticks)
    ax.set_xticklabels(names)
    ax.set_yticks(ticks)
    ax.set_yticklabels(names)
    ax.set_xlabel("predicted")
    ax.set_ylabel("true")
    ax.set_title(title)
    if save is not None:
        save_figure(fig, save)
    return fig

save_figure(fig, path, dpi=150, close=True)

Save a figure to disk and optionally close it.

Source code in src/cds2/viz.py
185
186
187
188
189
190
191
192
def save_figure(fig: Figure, path: str | Path, dpi: int = 150, close: bool = True) -> Path:
    """Save a figure to disk and optionally close it."""
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(target, dpi=dpi, bbox_inches="tight")
    if close:
        matplotlib.pyplot.close(fig)
    return target