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

Matplotlib中如何调整坐标轴刻度线尺寸以节省空间?

解决Matplotlib刻度线尺寸与标签间距问题

要解决刻度线过大、标签离坐标轴过远的问题,只需在tick_params中添加两个关键参数即可:

  • 用length参数缩小刻度线长度
  • 用pad参数减小标签与坐标轴的间距

修改后的可复现代码如下:

import numpy as np
import matplotlib.pyplot as plt
labels = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(6, 3.5),dpi=300)
plt.subplots_adjust(wspace=0.025, hspace=0.2)
for ax in [a for b in axes for a in b]:
    ax.imshow(np.random.randint(2, size=(22,42)))
    ax.set_xticks([0,6,12,18,24,30,36,41])
    # 修改X轴tick_params:添加length缩小刻度线,pad让标签贴近轴
    ax.tick_params(axis='x', which='major', labelsize=3, length=1, pad=1)
    ax.set_yticks([])
    ax.set_aspect('equal')
for ax in [item for sublist in axes for item in sublist][0::3]:
    ax.set_yticks(range(len(labels)))
    # Y轴同样调整pad参数让标签贴近
    ax.set_yticklabels(labels,fontsize=3)
    ax.tick_params(axis='y', which='major', length=1, pad=1)
fig.savefig("example.png",bbox_inches='tight')

关键参数说明

  • length:直接控制刻度线的像素长度,根据需求设置为1或更小的数值即可缩小刻度线
  • pad:控制刻度标签与坐标轴之间的像素距离,减小该值就能让标签更贴近坐标轴

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:50:54