You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制混淆矩阵时轴标签无法显示问题求助

解决Matplotlib轴标签被Seaborn Heatmap覆盖的问题

你遇到的问题核心是Seaborn的heatmap()函数在绘制过程中会重置Matplotlib Axes对象的轴标签,导致你提前设置的set_xlabel()和set_ylabel()被覆盖;另外画布布局不当也可能让标签被边缘截断,进而无法显示。

这里有两种直接有效的解决方案:

方案1:调整绘图顺序,先画热图再设置标签

把热图绘制放在轴标签设置之前,这样后续设置的标签就不会被覆盖。修改后的代码如下:

import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd

def plot_pairs_characters_errors_confusion_matrix(self, title="Confusion matrix of reccurent error characters pairs", family='serif', color='black', weight='normal', size=10, font_scale=1, display_html=True):
    # dataset
    df_cm = pd.DataFrame(self.confusion_matrix_pair_char_errors, self.letters_normalize, self.letters_normalize)
    fig_matrix, axes = plt.subplots()
    FONT = {'family': family, 'color': color, 'weight': weight, 'size': size, }
    
    # 先绘制热图
    sn.set(font_scale=font_scale)
    ax = sn.heatmap(df_cm, annot=True, annot_kws={"size": 8}, cmap="nipy_spectral_r", ax=axes)
    
    # 再设置标题和轴标签
    ax.set_title(f'{title}\n', fontdict=FONT)
    ax.set_xlabel('Predicted sentence', fontdict=FONT)
    ax.set_ylabel('Reference sentence', fontdict=FONT)
    
    # 可选:调整布局,防止标签被画布边缘截断
    plt.tight_layout()
    
    if display_html:
        return fig_matrix
    else:
        return plt.show()

方案2:在heatmap中直接指定配置并统一设置标签

你也可以在调用heatmap()时明确控制刻度,同时用set()方法一次性配置所有文本内容:

# 绘制热图时指定刻度标签
ax = sn.heatmap(df_cm, annot=True, annot_kws={"size": 8}, cmap="nipy_spectral_r", 
                ax=axes, xticklabels=self.letters_normalize, yticklabels=self.letters_normalize)
# 统一设置标题和轴标签
ax.set(xlabel='Predicted sentence', ylabel='Reference sentence', title=f'{title}\n', fontdict=FONT)
# 调整布局避免截断
plt.tight_layout()

问题根源解释

Seaborn的heatmap()是基于Matplotlib构建的,但它会对传入的Axes对象做一系列默认配置,包括重置轴标签、调整刻度样式等。如果你在绘制热图之前设置标签,这些自定义设置会被heatmap()的默认行为覆盖;而plt.tight_layout()可以自动调整画布元素的位置,避免标签被画布边缘截断的情况。

内容的提问来源于stack exchange,提问作者Lter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:47:45