Skip to content

Visualization

Plotting helpers for model validation, uncertainty diagnostics, dimensionality reduction, finite-pool Bayesian-optimization benchmarks, and closed-loop BO campaign progress.

matgpr.visualization

plot_parity(y_train_true, y_train_pred, *, y_train_std=None, y_test_true=None, y_test_pred=None, y_test_std=None, ax=None, figsize=(6.5, 6.5), title='Parity Plot', xlabel='True values', ylabel='Predicted values', save_path=None, dpi=300)

Plot true versus predicted values with optional uncertainty bars.

If test predictions are supplied, the metric annotation is calculated from the test set. Otherwise, training metrics are shown.

Source code in matgpr/visualization.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def plot_parity(
    y_train_true,
    y_train_pred,
    *,
    y_train_std=None,
    y_test_true=None,
    y_test_pred=None,
    y_test_std=None,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6.5, 6.5),
    title: str = "Parity Plot",
    xlabel: str = "True values",
    ylabel: str = "Predicted values",
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot true versus predicted values with optional uncertainty bars.

    If test predictions are supplied, the metric annotation is calculated from
    the test set. Otherwise, training metrics are shown.
    """
    y_train_true = _to_1d_array(y_train_true)
    y_train_pred = _to_1d_array(y_train_pred)
    y_train_std = None if y_train_std is None else _to_1d_array(y_train_std)

    fig, ax = _resolve_axes(ax, figsize)
    ax.errorbar(
        y_train_true,
        y_train_pred,
        yerr=y_train_std,
        fmt="o",
        color="gray",
        ecolor="gray",
        elinewidth=1.0,
        capsize=2,
        alpha=0.65,
        markersize=6,
        markeredgecolor="black",
        markeredgewidth=0.4,
        label="Train",
    )

    all_true = [y_train_true]
    all_pred = [y_train_pred]
    metric_true = y_train_true
    metric_pred = y_train_pred
    metric_label = "Train"

    if y_test_true is not None and y_test_pred is not None:
        y_test_true = _to_1d_array(y_test_true)
        y_test_pred = _to_1d_array(y_test_pred)
        y_test_std = None if y_test_std is None else _to_1d_array(y_test_std)
        ax.errorbar(
            y_test_true,
            y_test_pred,
            yerr=y_test_std,
            fmt="o",
            color="tab:blue",
            ecolor="tab:blue",
            elinewidth=1.2,
            capsize=2,
            alpha=0.9,
            markersize=7,
            markeredgecolor="black",
            markeredgewidth=0.5,
            label="Test",
        )
        all_true.append(y_test_true)
        all_pred.append(y_test_pred)
        metric_true = y_test_true
        metric_pred = y_test_pred
        metric_label = "Test"

    metrics = regression_metrics(metric_true, metric_pred)
    ax.text(
        0.05,
        0.95,
        f"{metric_label} metrics\n$R^2$ = {metrics['R2']:.3f}\nPearson r = {metrics['r']:.3f}",
        transform=ax.transAxes,
        va="top",
        ha="left",
        fontsize=11,
        bbox=dict(boxstyle="round", facecolor="white", edgecolor="gray", alpha=0.9),
    )

    all_true_values = np.concatenate(all_true)
    all_pred_values = np.concatenate(all_pred)
    min_val = min(all_true_values.min(), all_pred_values.min())
    max_val = max(all_true_values.max(), all_pred_values.max())
    padding = 0.05 * (max_val - min_val) if max_val > min_val else 1.0
    min_val -= padding
    max_val += padding

    ax.plot(
        [min_val, max_val], [min_val, max_val], "--", linewidth=1.5, color="black", label="Ideal"
    )
    ax.set_xlim(min_val, max_val)
    ax.set_ylim(min_val, max_val)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    ax.legend(frameon=False)
    ax.grid(True, alpha=0.25)
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax

plot_distribution(values, *, bins=30, density=False, color='tab:blue', alpha=0.8, ax=None, figsize=(6, 4.5), title='Distribution Plot', xlabel='Value', ylabel=None, show_mean=True, show_median=True, save_path=None, dpi=300)

Plot a histogram with optional mean and median markers.

Source code in matgpr/visualization.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def plot_distribution(
    values,
    *,
    bins: int | str = 30,
    density: bool = False,
    color: str = "tab:blue",
    alpha: float = 0.8,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6, 4.5),
    title: str = "Distribution Plot",
    xlabel: str = "Value",
    ylabel: str | None = None,
    show_mean: bool = True,
    show_median: bool = True,
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot a histogram with optional mean and median markers."""
    values = _to_1d_array(values)
    values = values[~np.isnan(values)]
    if values.size == 0:
        raise ValueError("No valid numeric values provided")

    fig, ax = _resolve_axes(ax, figsize)
    ax.hist(
        values,
        bins=bins,
        density=density,
        color=color,
        alpha=alpha,
        edgecolor="black",
        linewidth=0.8,
    )

    if show_mean:
        mean_value = np.mean(values)
        ax.axvline(
            mean_value, color="red", linestyle="--", linewidth=2, label=f"Mean = {mean_value:.3f}"
        )
    if show_median:
        median_value = np.median(values)
        ax.axvline(
            median_value,
            color="darkorange",
            linestyle="-.",
            linewidth=2,
            label=f"Median = {median_value:.3f}",
        )

    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel or ("Density" if density else "Count"))
    ax.grid(True, alpha=0.25)
    if show_mean or show_median:
        ax.legend(frameon=False)
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax

plot_correlation_matrix(df, *, columns=None, method='pearson', ax=None, figsize=(8, 6), title='Correlation Matrix', cmap='coolwarm', annotate=True, fmt='.2f', save_path=None, dpi=300)

Plot a numeric feature correlation matrix and return the correlation table.

Source code in matgpr/visualization.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def plot_correlation_matrix(
    df: pd.DataFrame,
    *,
    columns: list[str] | None = None,
    method: str = "pearson",
    ax: Axes | None = None,
    figsize: tuple[float, float] = (8, 6),
    title: str = "Correlation Matrix",
    cmap: str = "coolwarm",
    annotate: bool = True,
    fmt: str = ".2f",
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot a numeric feature correlation matrix and return the correlation table."""
    if columns is None:
        data = df.select_dtypes(include=np.number)
    else:
        missing = [column for column in columns if column not in df.columns]
        if missing:
            raise KeyError(f"Columns not found in dataframe: {missing}")
        data = df[columns].select_dtypes(include=np.number)

    if data.shape[1] < 2:
        raise ValueError("At least two numeric columns are required")

    corr = data.corr(method=method)
    fig, ax = _resolve_axes(ax, figsize)
    image = ax.imshow(corr, cmap=cmap, vmin=-1, vmax=1, aspect="auto")
    colorbar = fig.colorbar(image, ax=ax)
    colorbar.set_label(f"{method.title()} correlation")

    ax.set_xticks(np.arange(len(corr.columns)))
    ax.set_yticks(np.arange(len(corr.columns)))
    ax.set_xticklabels(corr.columns, rotation=45, ha="right")
    ax.set_yticklabels(corr.columns)

    if annotate:
        for i in range(len(corr.columns)):
            for j in range(len(corr.columns)):
                value = corr.iloc[i, j]
                ax.text(
                    j,
                    i,
                    format(value, fmt),
                    ha="center",
                    va="center",
                    fontsize=8,
                    color="black" if abs(value) < 0.6 else "white",
                )

    ax.set_title(title)
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax, corr

plot_learning_curve(df, *, train_size_col='train_size', metric_col='test_R2', metric=None, split='test', x_axis='percent', model_col='model', models=None, ax=None, figsize=(7, 5), title=None, ylabel=None, save_path=None, dpi=300)

Plot mean metric versus train-set size for one or more models.

Repeated runs at the same train size are averaged. Error bars show one standard deviation across runs. Use x_axis="percent" to show training data in percent, x_axis="count" to show sample counts, or x_axis="fraction" to show the raw fraction. Use metric and split as a convenient alternative to a full metric column name. For example, metric="RMSE", split="test" resolves to test_RMSE and metric="RMSE", split=("train", "test") plots both train and test RMSE curves.

Source code in matgpr/visualization.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def plot_learning_curve(
    df: pd.DataFrame,
    *,
    train_size_col: str = "train_size",
    metric_col: str | Sequence[str] | None = "test_R2",
    metric: str | None = None,
    split: str | Sequence[str] = "test",
    x_axis: str = "percent",
    model_col: str = "model",
    models: list[str] | None = None,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (7, 5),
    title: str | None = None,
    ylabel: str | None = None,
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot mean metric versus train-set size for one or more models.

    Repeated runs at the same train size are averaged. Error bars show one
    standard deviation across runs. Use ``x_axis="percent"`` to show training
    data in percent, ``x_axis="count"`` to show sample counts, or
    ``x_axis="fraction"`` to show the raw fraction. Use ``metric`` and
    ``split`` as a convenient alternative to a full metric column name. For
    example, ``metric="RMSE", split="test"`` resolves to ``test_RMSE`` and
    ``metric="RMSE", split=("train", "test")`` plots both train and test
    RMSE curves.
    """
    metric_columns = _resolve_learning_curve_metric_columns(
        metric_col=metric_col,
        metric=metric,
        split=split,
    )

    plot_df = df.copy()
    x_col, x_label = _resolve_learning_curve_x_axis(
        plot_df,
        train_size_col=train_size_col,
        x_axis=x_axis,
    )

    required = [x_col, model_col, *metric_columns]
    missing = [column for column in required if column not in plot_df.columns]
    if missing:
        raise KeyError(f"Missing required columns: {missing}")

    if models is not None:
        plot_df = plot_df[plot_df[model_col].isin(models)]
    if plot_df.empty:
        raise ValueError("No data available after filtering models")

    metric_frames = []
    for column in metric_columns:
        split_name, metric_name = _metric_column_parts(column)
        metric_frame = plot_df[[model_col, x_col, column]].rename(columns={column: "metric_value"})
        metric_frame["metric_col"] = column
        metric_frame["split"] = split_name
        metric_frame["metric"] = metric_name
        metric_frames.append(metric_frame)

    long_df = pd.concat(metric_frames, ignore_index=True)
    summary = (
        long_df.groupby([model_col, "metric_col", "split", "metric", x_col], dropna=False)
        .agg(
            metric_mean=("metric_value", "mean"),
            metric_std=("metric_value", "std"),
            n_runs=("metric_value", "count"),
        )
        .reset_index()
        .sort_values([x_col, model_col, "metric_col"])
    )
    summary["metric_std"] = summary["metric_std"].fillna(0.0)

    fig, ax = _resolve_axes(ax, figsize)
    markers = ["o", "s", "^", "D", "v", "P", "X"]
    linestyles = ["-", "--", "-.", ":"]

    curve_keys = (
        summary[[model_col, "metric_col"]].drop_duplicates().itertuples(index=False, name=None)
    )
    for i, (model_name, metric_column) in enumerate(curve_keys):
        model_data = summary[
            (summary[model_col] == model_name) & (summary["metric_col"] == metric_column)
        ]
        label = _learning_curve_label(
            model_name,
            metric_column,
            multiple_metrics=len(metric_columns) > 1,
        )
        ax.errorbar(
            model_data[x_col],
            model_data["metric_mean"],
            yerr=model_data["metric_std"],
            fmt=markers[i % len(markers)] + linestyles[i % len(linestyles)],
            elinewidth=1.3,
            capsize=3,
            markersize=7,
            linewidth=2.2,
            label=label,
        )

    y_axis_label = ylabel or _learning_curve_y_label(metric=metric, metric_columns=metric_columns)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_axis_label)
    ax.set_title(title or f"{y_axis_label} vs Train Set Size")
    ax.set_xticks(sorted(summary[x_col].unique()))
    if all(
        column.lower() in {"test_r2", "train_r2", "r2", "test_r", "train_r", "r"}
        for column in metric_columns
    ):
        ax.set_ylim(0.0, 1.05)
    ax.grid(True, alpha=0.25)
    ax.legend(frameon=False, loc="best")
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax, summary

plot_bo_benchmark_trace(history, *, value_col='matgpr_best_so_far', strategy_col='matgpr_strategy', evaluation_col='matgpr_evaluation', strategies=None, show_std=True, std_style='band', markers=True, ax=None, figsize=(7, 5), title=None, xlabel='Evaluated candidates', ylabel=None, save_path=None, dpi=300)

Plot repeated finite-pool BO benchmark traces.

The expected input is the history table returned by compare_bo_strategies or simulate_bo_strategy. Repeated runs at the same strategy and evaluation count are averaged. When show_std=True, one standard deviation across repeated replays is drawn as either a shaded band or error bars.

Source code in matgpr/visualization.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
def plot_bo_benchmark_trace(
    history: pd.DataFrame,
    *,
    value_col: str = "matgpr_best_so_far",
    strategy_col: str = "matgpr_strategy",
    evaluation_col: str = "matgpr_evaluation",
    strategies: Sequence[str] | None = None,
    show_std: bool = True,
    std_style: str = "band",
    markers: bool = True,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (7, 5),
    title: str | None = None,
    xlabel: str = "Evaluated candidates",
    ylabel: str | None = None,
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot repeated finite-pool BO benchmark traces.

    The expected input is the ``history`` table returned by
    ``compare_bo_strategies`` or ``simulate_bo_strategy``. Repeated runs at the
    same strategy and evaluation count are averaged. When ``show_std=True``,
    one standard deviation across repeated replays is drawn as either a shaded
    band or error bars.
    """
    plot_df, strategy_order = _prepare_bo_trace_dataframe(
        history,
        strategy_col=strategy_col,
        evaluation_col=evaluation_col,
        value_col=value_col,
        strategies=strategies,
    )
    summary = _summarize_bo_trace(
        plot_df,
        strategy_col=strategy_col,
        evaluation_col=evaluation_col,
        value_col=value_col,
    )
    std_style = _normalize_std_style(std_style)

    fig, ax = _resolve_axes(ax, figsize)
    marker_styles = ["o", "s", "^", "D", "v", "P", "X"]
    linestyles = ["-", "--", "-.", ":"]

    for i, strategy_name in enumerate(strategy_order):
        strategy_data = summary.loc[summary[strategy_col] == strategy_name]
        if strategy_data.empty:
            continue
        x_values = strategy_data[evaluation_col].to_numpy(dtype=float)
        means = strategy_data["value_mean"].to_numpy(dtype=float)
        stds = strategy_data["value_std"].to_numpy(dtype=float)
        marker = marker_styles[i % len(marker_styles)] if markers else None
        linestyle = linestyles[i % len(linestyles)]

        if show_std and std_style == "errorbar":
            ax.errorbar(
                x_values,
                means,
                yerr=stds,
                fmt=marker or "",
                linestyle=linestyle,
                elinewidth=1.2,
                capsize=3,
                markersize=6,
                linewidth=2.1,
                label=str(strategy_name),
            )
        else:
            (line,) = ax.plot(
                x_values,
                means,
                marker=marker,
                linestyle=linestyle,
                markersize=6,
                linewidth=2.1,
                label=str(strategy_name),
            )
            if show_std and std_style == "band":
                ax.fill_between(
                    x_values,
                    means - stds,
                    means + stds,
                    color=line.get_color(),
                    alpha=0.16,
                    linewidth=0,
                )

    y_axis_label = ylabel or _bo_trace_y_label(value_col)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(y_axis_label)
    ax.set_title(title or f"{y_axis_label} vs BO Evaluations")
    _set_integer_xticks_if_compact(ax, summary[evaluation_col])
    ax.grid(True, alpha=0.25)
    ax.legend(frameon=False, loc="best")
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax, summary

plot_bo_regret_trace(history, *, value_col='matgpr_simple_regret', strategy_col='matgpr_strategy', evaluation_col='matgpr_evaluation', strategies=None, show_std=True, std_style='band', markers=True, ax=None, figsize=(7, 5), title=None, xlabel='Evaluated candidates', ylabel='Simple regret', save_path=None, dpi=300)

Plot simple regret from repeated finite-pool BO benchmarks.

Source code in matgpr/visualization.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def plot_bo_regret_trace(
    history: pd.DataFrame,
    *,
    value_col: str = "matgpr_simple_regret",
    strategy_col: str = "matgpr_strategy",
    evaluation_col: str = "matgpr_evaluation",
    strategies: Sequence[str] | None = None,
    show_std: bool = True,
    std_style: str = "band",
    markers: bool = True,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (7, 5),
    title: str | None = None,
    xlabel: str = "Evaluated candidates",
    ylabel: str = "Simple regret",
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot simple regret from repeated finite-pool BO benchmarks."""
    return plot_bo_benchmark_trace(
        history,
        value_col=value_col,
        strategy_col=strategy_col,
        evaluation_col=evaluation_col,
        strategies=strategies,
        show_std=show_std,
        std_style=std_style,
        markers=markers,
        ax=ax,
        figsize=figsize,
        title=title or "Simple Regret vs BO Evaluations",
        xlabel=xlabel,
        ylabel=ylabel,
        save_path=save_path,
        dpi=dpi,
    )

plot_bo_campaign_progress(log_data, *, campaign_id=None, target_column=None, maximize=True, campaign_col='matgpr_campaign_id', iteration_col='matgpr_iteration', record_type_col='matgpr_record_type', observation_record_type='observation', ax=None, figsize=(7, 5), title=None, xlabel='BO iteration', ylabel=None, save_path=None, dpi=300)

Plot closed-loop BO campaign progress from a log dataframe or CSV path.

With target_column=None, the plot shows the number of recommendation, selection, and observation records logged at each iteration. With target_column supplied, the plot shows the best observed target value so far across observation records.

Source code in matgpr/visualization.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
def plot_bo_campaign_progress(
    log_data: pd.DataFrame | str | Path,
    *,
    campaign_id: str | None = None,
    target_column: str | None = None,
    maximize: bool = True,
    campaign_col: str = "matgpr_campaign_id",
    iteration_col: str = "matgpr_iteration",
    record_type_col: str = "matgpr_record_type",
    observation_record_type: str = "observation",
    ax: Axes | None = None,
    figsize: tuple[float, float] = (7, 5),
    title: str | None = None,
    xlabel: str = "BO iteration",
    ylabel: str | None = None,
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot closed-loop BO campaign progress from a log dataframe or CSV path.

    With ``target_column=None``, the plot shows the number of recommendation,
    selection, and observation records logged at each iteration. With
    ``target_column`` supplied, the plot shows the best observed target value
    so far across observation records.
    """
    log = _prepare_bo_campaign_log(
        log_data,
        campaign_id=campaign_id,
        campaign_col=campaign_col,
        iteration_col=iteration_col,
        record_type_col=record_type_col,
    )
    if target_column is None:
        summary = _summarize_bo_campaign_record_counts(
            log,
            iteration_col=iteration_col,
            record_type_col=record_type_col,
        )
        fig, ax = _plot_bo_campaign_record_counts(
            summary,
            iteration_col=iteration_col,
            record_type_col=record_type_col,
            ax=ax,
            figsize=figsize,
            title=title,
            xlabel=xlabel,
            ylabel=ylabel,
        )
    else:
        summary = _summarize_bo_campaign_target_progress(
            log,
            target_column=target_column,
            maximize=maximize,
            iteration_col=iteration_col,
            record_type_col=record_type_col,
            observation_record_type=observation_record_type,
        )
        fig, ax = _plot_bo_campaign_target_progress(
            summary,
            target_column=target_column,
            iteration_col=iteration_col,
            maximize=maximize,
            ax=ax,
            figsize=figsize,
            title=title,
            xlabel=xlabel,
            ylabel=ylabel,
        )

    _save_figure(fig, save_path, dpi)
    return fig, ax, summary

plot_pca_scree(pca, *, ax=None, figsize=(6, 4), title='PCA Scree Plot')

Plot explained variance and cumulative variance from a fitted PCA.

Source code in matgpr/visualization.py
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
def plot_pca_scree(
    pca,
    *,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6, 4),
    title: str = "PCA Scree Plot",
):
    """Plot explained variance and cumulative variance from a fitted PCA."""
    explained = pca.explained_variance_ratio_
    components = np.arange(1, len(explained) + 1)
    cumulative = np.cumsum(explained)

    fig, ax = _resolve_axes(ax, figsize)
    ax.bar(components, explained, alpha=0.7, label="Explained variance")
    ax.plot(components, cumulative, marker="o", label="Cumulative variance")
    ax.set_xlabel("Principal component")
    ax.set_ylabel("Variance ratio")
    ax.set_title(title)
    ax.set_xticks(components)
    ax.set_ylim(0, 1.05)
    ax.legend(frameon=False)
    ax.grid(True, alpha=0.3)
    fig.tight_layout()
    return fig, ax

plot_pca_scores(train_scores, *, test_scores=None, pc_x='PC1', pc_y='PC2', ax=None, figsize=(6, 5), title='PCA Scores')

Plot PCA scores for training data and optionally overlay test data.

Source code in matgpr/visualization.py
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
def plot_pca_scores(
    train_scores: pd.DataFrame,
    *,
    test_scores: pd.DataFrame | None = None,
    pc_x: str = "PC1",
    pc_y: str = "PC2",
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6, 5),
    title: str = "PCA Scores",
):
    """Plot PCA scores for training data and optionally overlay test data."""
    _require_columns(train_scores, [pc_x, pc_y], "train_scores")
    if test_scores is not None:
        _require_columns(test_scores, [pc_x, pc_y], "test_scores")

    fig, ax = _resolve_axes(ax, figsize)
    ax.scatter(
        train_scores[pc_x],
        train_scores[pc_y],
        s=55,
        alpha=0.75,
        label="Train",
        edgecolor="k",
        linewidth=0.4,
    )

    if test_scores is not None:
        ax.scatter(
            test_scores[pc_x],
            test_scores[pc_y],
            s=75,
            alpha=0.95,
            label="Test",
            marker="^",
            edgecolor="k",
            linewidth=0.5,
        )

    ax.set_xlabel(pc_x)
    ax.set_ylabel(pc_y)
    ax.set_title(title)
    ax.legend(frameon=False)
    ax.grid(True, alpha=0.3)
    fig.tight_layout()
    return fig, ax

plot_uncertainty_calibration(y_true, y_pred, y_std, *, confidence_levels=None, ax=None, figsize=(6, 5), title='Uncertainty Calibration', save_path=None, dpi=300)

Plot observed versus expected Gaussian interval coverage.

Source code in matgpr/visualization.py
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
def plot_uncertainty_calibration(
    y_true,
    y_pred,
    y_std,
    *,
    confidence_levels=None,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6, 5),
    title: str = "Uncertainty Calibration",
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot observed versus expected Gaussian interval coverage."""
    curve = calibration_curve(
        y_true,
        y_pred,
        y_std,
        confidence_levels=confidence_levels,
    )

    fig, ax = _resolve_axes(ax, figsize)
    ax.plot(
        curve["expected_coverage"],
        curve["observed_coverage"],
        marker="o",
        linewidth=2.0,
        markersize=6,
        color="tab:blue",
        label="Model",
    )
    ax.plot([0, 1], [0, 1], "--", color="black", linewidth=1.4, label="Ideal")
    ax.set_xlabel("Expected coverage")
    ax.set_ylabel("Observed coverage")
    ax.set_title(title)
    ax.set_xlim(0.0, 1.0)
    ax.set_ylim(0.0, 1.0)
    ax.grid(True, alpha=0.25)
    ax.legend(frameon=False)
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax, curve

plot_uncertainty_vs_error(y_true, y_pred, y_std, *, ax=None, figsize=(6, 5), title='Uncertainty vs Error', save_path=None, dpi=300)

Plot predictive standard deviation versus absolute prediction error.

Source code in matgpr/visualization.py
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
def plot_uncertainty_vs_error(
    y_true,
    y_pred,
    y_std,
    *,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (6, 5),
    title: str = "Uncertainty vs Error",
    save_path: str | None = None,
    dpi: int = 300,
):
    """Plot predictive standard deviation versus absolute prediction error."""
    y_true = _to_1d_float_array(y_true, "y_true")
    y_pred = _to_1d_float_array(y_pred, "y_pred")
    y_std = _to_1d_float_array(y_std, "y_std")
    if not (len(y_true) == len(y_pred) == len(y_std)):
        raise ValueError("y_true, y_pred, and y_std must have the same length")
    if np.any(y_std <= 0):
        raise ValueError("y_std must contain only positive values")

    absolute_error = np.abs(y_true - y_pred)
    diagnostics = uncertainty_diagnostics(y_true, y_pred, y_std)

    fig, ax = _resolve_axes(ax, figsize)
    ax.scatter(
        y_std,
        absolute_error,
        s=55,
        alpha=0.8,
        color="tab:blue",
        edgecolor="black",
        linewidth=0.4,
    )
    ax.set_xlabel("Predictive standard deviation")
    ax.set_ylabel("Absolute prediction error")
    ax.set_title(title)
    ax.grid(True, alpha=0.25)
    ax.text(
        0.05,
        0.95,
        f"NLPD = {diagnostics['NLPD']:.3f}\n"
        f"Coverage = {diagnostics['observed_coverage']:.3f}\n"
        f"Spearman = {diagnostics['uncertainty_error_spearman']:.3f}",
        transform=ax.transAxes,
        va="top",
        ha="left",
        fontsize=10,
        bbox=dict(boxstyle="round", facecolor="white", edgecolor="gray", alpha=0.9),
    )
    fig.tight_layout()
    _save_figure(fig, save_path, dpi)
    return fig, ax, diagnostics