为何使用subplot时混淆矩阵旁会出现额外矩阵?
解决混淆矩阵subplot显示异常问题
你的代码出现异常的核心原因是plot_confusion_matrix会自动创建新的绘图画布,和plt.subplot的子图布局逻辑冲突,加上循环内频繁调用plt.show(),导致布局混乱和异常内容出现。以下是具体修改方案:
关键问题点
plot_confusion_matrix默认会新建独立figure,和你手动设置的subplot重复,导致子图区域出现额外的绘图元素plt.show()放在循环内部,每次循环都会单独显示当前图,破坏整体布局figsize参数应该在全局画布设置,而非传给plot_confusion_matrix
修改后的完整代码
def crossValidation(cla): i = 1 skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=2) acc = [] net_mat = np.zeros((4, 4)) # 提前创建全局画布,设置适配6行2列的尺寸 plt.figure(figsize=(12, 18)) for train_index, test_index in skf.split(X, Y): X_train = X[train_index] X_test = X[test_index] Y_train = Y[train_index] Y_test = Y[test_index] cla.fit(X_train, Y_train) Y_testPred = cla.predict(X_test) testAccuracy = metrics.accuracy_score(Y_test, Y_testPred) print("Test Accuracy", testAccuracy*100) acc.append(testAccuracy) matrix1 = confusion_matrix(Y_test, Y_testPred) net_mat = net_mat + matrix1 # 获取当前子图的轴对象 ax = plt.subplot(6, 2, i) # 强制在指定子图轴上绘制混淆矩阵,避免新建画布 plot_confusion_matrix(matrix1, class_names=['A', 'B','C','D'], show_normed=True, colorbar=True, show_absolute=True, ax=ax) i += 1 # 自动调整子图间距,避免标签重叠 plt.tight_layout() # 所有子图绘制完成后统一显示 plt.show() return net_mat, acc
额外说明
如果你的plot_confusion_matrix是自定义函数,本身不支持ax参数,需要修改函数内部逻辑,让它基于传入的轴对象绘图:
def plot_confusion_matrix(matrix, class_names, show_normed=True, colorbar=True, show_absolute=True, ax=None): # 优先使用传入的轴,否则获取当前轴 ax = ax or plt.gca() # 后续所有绘图操作都基于ax对象,比如: im = ax.imshow(matrix, cmap='Blues') if colorbar: plt.colorbar(im, ax=ax) # 设置类别标签 ax.set_xticks(np.arange(len(class_names))) ax.set_yticks(np.arange(len(class_names))) ax.set_xticklabels(class_names) ax.set_yticklabels(class_names) # 其他绘图逻辑...
内容的提问来源于stack exchange,提问作者Michał Jagodzinski
相关产品推荐
相关产品推荐

