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

如何隐藏Matplotlib绘图的坐标轴刻度线与侧边轴线

Matplotlib移除刻度标记与侧边轴线的实现方法

核心修改逻辑

  • 移除x/y轴刻度小标记:通过tick_params设置刻度线长度为0,不会影响已配置的刻度标签显示
  • 隐藏左右侧黑色轴线:获取当前轴对象,将左右侧的脊柱(spine)设置为不可见

修改后完整代码

import numpy as np
import matplotlib.pyplot as plt

normalised_confusion_matrix  = np.array(
[[160,1,0,1,0,0,1,1,1,2,2],
[4,46,0,0,0,0,0,0,0,0,0],
[3,0,77,0,0,0,0,0,0,0,0],
[12,0,0,136,0,0,0,0,0,0,0],
[11,0,0,0,55,0,0,0,0,0,0],
[22,0,0,0,0,66,0,0,0,0,0],
[1,0,0,0,0,0,26,0,0,0,0],
[27,0,0,0,0,0,0,232,0,0,0],
[10,0,1,0,0,0,0,0,60,0,0],
[6,0,0,0,0,0,0,0,0,37,0],
[12,0,0,0,0,0,0,0,0,0,71]]
)

classes = ['0', '1','2', '3', '4', '5', '6', '7', '8', '9', '10']

fig = plt.figure(figsize=(14, 10))
plt.imshow(
    normalised_confusion_matrix,
    interpolation='nearest',
    cmap=plt.cm.rainbow
)
plt.title("Confusion Matrix", fontsize=15, weight='bold')
cbar = plt.colorbar()
cbar.ax.tick_params(labelsize=15)

tick_marks = np.arange(11)
plt.xticks(tick_marks, classes, rotation=35, fontsize=10, weight='bold')
plt.yticks(tick_marks, classes, rotation=35, fontsize=10, weight='bold')

# 移除x、y轴的刻度小标记
plt.tick_params(axis='both', which='both', length=0)
# 隐藏左右两侧的黑色轴线
ax = plt.gca()
ax.spines[['left', 'right']].set_visible(False)

plt.tight_layout()
plt.grid(False)
plt.ylabel('Groundtruth label', fontsize=13, weight='bold')
plt.xlabel('Predicted label', fontsize=13, weight='bold')
plt.show()

补充说明

如果你需要同时隐藏上下侧的轴线,只需要把ax.spines[['left', 'right']].set_visible(False)修改为ax.spines[['left', 'right', 'top', 'bottom']].set_visible(False)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:36:04