Matplotlib绘制混淆矩阵时Y轴标签无法显示的问题
问题
我为这段混淆矩阵可视化代码尝试了约15种设置Y轴标签的方法,目前只能直接将行标注为Predicted Positive和Predicted Negative,但我希望像Actual一样将Predicted放在表格外侧。我猜测这和绘制表格有关,但移除行标签也无法解决问题。
代码如下:
def plot_conf_mat(data, model_name): ''' Plot a confusion matrix based on the array data. Expected: 2x2 matrix of form [[TP, FP], [FN, TN]]. Outputs a simple colored confusion matrix table ''' #set fontsizes SMALL_SIZE = 20 MEDIUM_SIZE = 25 BIGGER_SIZE = 30 plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=SMALL_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title # Prepare table columns = ('Positive', 'Negative') rows = ('Predicted\nPositive', 'Predicted\nNegative') cell_text = data # Add a table at the bottom of the axes colors = [["tab:green","tab:red"],[ "tab:red","tab:grey"]] fig, ax = plt.subplots(figsize = (6,5)) ax.axis('tight') ax.axis('off') the_table = ax.table(cellText=cell_text,cellColours=colors, colLabels=columns, rowLabels = rows, loc='center') the_table.scale(2,5) the_table.set_fontsize(20) #apparently it doesnt adhere to plt.rc?? ax.set_title(f'{model_name} Confusion Matrix: \n\nActual') ax.set_ylabel('Predicted') #doesn't work!! fig.savefig(f"{model_name}_conf_mat.pdf", bbox_inches = 'tight') plt.show()
输出结果(模型名称已打码):
解决方案
核心问题是你调用了ax.axis('off'),这会隐藏整个坐标轴系统,包括Y轴标签,所以ax.set_ylabel完全不会生效。要实现把Predicted放在表格外侧的效果,可按以下方式修改:
修改后的代码
def plot_conf_mat(data, model_name): ''' 绘制基于数组数据的混淆矩阵 输入格式:2x2矩阵 [[TP, FP], [FN, TN]] 输出带颜色的混淆矩阵表格 ''' # 设置字体大小 SMALL_SIZE = 20 MEDIUM_SIZE = 25 BIGGER_SIZE = 30 plt.rc('font', size=MEDIUM_SIZE) # 控制默认文本大小 plt.rc('axes', titlesize=MEDIUM_SIZE) # 坐标轴标题字体大小 plt.rc('axes', labelsize=SMALL_SIZE) # X/Y轴标签字体大小 plt.rc('xtick', labelsize=SMALL_SIZE) # X轴刻度字体大小 plt.rc('ytick', labelsize=SMALL_SIZE) # Y轴刻度字体大小 plt.rc('legend', fontsize=SMALL_SIZE) # 图例字体大小 plt.rc('figure', titlesize=BIGGER_SIZE) # 图表标题字体大小 # 准备表格数据 columns = ('Positive', 'Negative') # 行标签仅保留状态描述,移除Predicted前缀 rows = ('Positive', 'Negative') cell_text = data colors = [["tab:green","tab:red"],["tab:red","tab:grey"]] fig, ax = plt.subplots(figsize=(6,5)) ax.axis('tight') ax.axis('off') the_table = ax.table(cellText=cell_text, cellColours=colors, colLabels=columns, rowLabels=rows, loc='center') the_table.scale(2,5) the_table.set_fontsize(20) # 调整标题位置,让Actual与表格间距更合理 ax.set_title(f'{model_name} Confusion Matrix: \n\nActual', y=1.05) # 手动添加Predicted标签,定位在表格左侧居中位置 ax.text(-0.3, 0.5, 'Predicted', fontsize=SMALL_SIZE, ha='center', va='center', rotation='vertical') fig.savefig(f"{model_name}_conf_mat.pdf", bbox_inches='tight') plt.show()
关键说明
ax.text的坐标参数-0.3和0.5是基于坐标轴的相对位置(范围0-1),可根据表格实际大小微调,确保标签与表格对齐- 因为已经关闭了坐标轴,必须通过手动添加文本的方式实现外侧标签,无法使用常规轴标签方法
- 调整标题的
y参数(y=1.05),让顶部的Actual标签与表格布局更协调
内容的提问来源于stack exchange,提问作者Daniel Frees
相关产品推荐
相关产品推荐

