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

如何在matplotlib的imshow热力图中将x、y刻度移至像素中心?

解决热力图刻度居中的问题

嘿,我之前做热力图的时候也被这个问题卡过!其实只需要简单调整坐标轴的刻度位置和标签就能搞定,下面是修改后的完整代码和思路解释:

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

def plot():
    intensity = np.random.rand(10,10)
    matrix_intensity = np.matrix(intensity)
    max_intensity = matrix_intensity.max()
    min_intensity = matrix_intensity.min()

    # 创建热力图画布和轴对象
    fig, ax = plt.subplots()
    im = ax.imshow(intensity, cmap='viridis', vmin=min_intensity, vmax=max_intensity)

    # 核心操作:把刻度移到像素块中心
    # 10x10的矩阵,每个像素块的中心坐标是 0.5,1.5,...,9.5
    ax.set_xticks(np.arange(intensity.shape[1]) + 0.5)
    ax.set_yticks(np.arange(intensity.shape[0]) + 0.5)

    # 保留原有的整数刻度标签
    ax.set_xticklabels(np.arange(intensity.shape[1]))
    ax.set_yticklabels(np.arange(intensity.shape[0]))

    # 可选:添加颜色条增强可读性
    plt.colorbar(im)
    plt.show()

plot()

关键逻辑说明

  • imshow默认把每个像素块的左下角对齐整数坐标(比如第一个块对应(0,0)左下角),所以每个块的中心位置就是整数+0.5。
  • 通过set_xticks把刻度线移到中心位置,再用set_xticklabels保留原有的整数标签,视觉上就实现了刻度和像素块中心的对应。

如果你的热力图是用pcolor/pcolormesh绘制的,逻辑完全一致,只需要把刻度位置调整为单元格中心坐标即可。

内容的提问来源于stack exchange,提问作者A.Piquer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:43