"""SCI Figure Hub — Normalized Confusion Matrix (CC0-1.0)""" PALETTE = ["#F7FBFF", "#6BAED6", "#08306B"] import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list("sci_palette", PALETTE) plt.rcParams.update({"font.sans-serif": ["Arial", "DejaVu Sans"], "font.size": 8, "pdf.fonttype": 42}) classes = ["Class A", "Class B", "Class C", "Class D"] cm = np.array([[92, 4, 2, 2], [3, 88, 6, 3], [1, 5, 91, 3], [2, 2, 4, 92]]) cm_norm = cm / cm.sum(axis=1, keepdims=True) fig, ax = plt.subplots(figsize=(3.3, 2.95), dpi=300) im = ax.pcolormesh(np.arange(cm_norm.shape[1] + 1) - 0.5, np.arange(cm_norm.shape[0] + 1) - 0.5, cm_norm, cmap=cmap, vmin=0, vmax=1) ax.set_aspect("equal") ax.invert_yaxis() ax.set_xticks(range(4), classes, rotation=20, ha="right") ax.set_yticks(range(4), classes) for i in range(4): for j in range(4): ax.text(j, i, f"{cm_norm[i, j]*100:.1f}%\n({cm[i, j]})", ha="center", va="center", fontsize=6.8, color="#FFFFFF" if cm_norm[i, j] > 0.55 else "#121C26") ax.set_xlabel("Predicted Label") ax.set_ylabel("True Label") fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="Recall") fig.tight_layout() fig.savefig("confusion_matrix.pdf", bbox_inches="tight")