python-3.x - 我的 matplot 的网格偏离了 -0.5

标签 python-3.x matplotlib matplotlib-basemap color-mapping matplotlib-widget

我正在尝试使用 matplotlib 库和 python 3 将颜色映射应用于二维数组。为了简单起见,我制作了一个示例代码来显示我的问题:

示例代码:

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

    #just an example array
    sample= np.zeros((20,20),dtype=int)
    sample[2,2]=sample[4,4]=2
    #color-table and color bounds
    cmap = colors.ListedColormap(['black','white','red','green'])
    bounds=[-6,0,1,99,105]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    fig, ax = plt.subplots()
    ax.imshow(sample,interpolation='nearest', cmap=cmap, norm=norm)
    ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
    ax.set_xlim(0, 20)
    ax.set_ylim(20, 0)

    ax.set_xticks(np.arange(0,20,1))
    ax.set_yticks(np.arange(0,20,1))
    plt.show()

使用此代码,我有一个 20 x 20 的网格,除了 [2,2][4,4] 两个单元格之外,网格到处都是白色的是红色的。问题是,当我显示网格时,单元格在两个方向上都偏离了 -0.5。我通过这个示例代码得到的是: enter image description here

如果我将网格移动 -0.5:

    ax.set_xticks(np.arange(-0.5,20,1))
    ax.set_yticks(np.arange(-0.5,20,1))

然后我的单元格看起来是正确的,但现在网格全错了! enter image description here

我的代码有什么问题吗?我真的不明白这是怎么发生的?

最佳答案

ax.imshow 文档字符串的注释部分说:

Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).

所以你的电话变成:

ax.imshow(sample, interpolation='none', cmap=cmap, norm=norm,
          extent=[0, 20, 20, 0])

关于python-3.x - 我的 matplot 的网格偏离了 -0.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043810/

相关文章:

python - 如何解析 CSS URL 中的特定值

python - 代码从 python 2.7 到 3.5 (unicode)

matplotlib - Seaborn regplot 创建重复轴

python - 使用匀称多边形进行映射

python - 对 python 列表中的相关值求和

python - 如何将列表列表打印为合理的表格格式

python - 将图例添加到散点图 (PCA)

适用于 Windows、matplotlib 和 opencv 的 Python

Python - 动画 basemap 散点图

Python:使用shiftgrid改变经度