Matplotlib 的 matshow 未与网格对齐

Matplotlib's matshow not aligned with grid

我有一个代表网格的 6x6 矩阵。在该网格的一部分,我有一个较小的网格 (3x3),如下所示:

In [65]:

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1
arr
Out[65]:
array([[ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

我想绘制它,但 matplotlib 未对齐它,如下所示。红色方块应该覆盖水平和垂直轴上从 0 到 3 的区域。

In [88]:

plt.matshow(arr)
plt.grid()

我该如何解决这个问题?谢谢

如果您愿意,可以使用:

matshow(arr, extent=[0, 6, 0, 6])

但是,标准行为符合预期:以 (0, 0) 为中心的像素具有元素 (0, 0) 的值。

您可以对标签使用主刻度,对网格使用次刻度。

考虑:

import matplotlib.pyplot as plt
import numpy as np

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1

plt.matshow(arr)

# This is very hack-ish
plt.gca().set_xticks([x - 0.5 for x in plt.gca().get_xticks()][1:], minor='true')
plt.gca().set_yticks([y - 0.5 for y in plt.gca().get_yticks()][1:], minor='true')
plt.grid(which='minor')

plt.show()

其中显示:

诀窍就是这两行:

plt.gca().set_xticks(..., minor='true')
plt.grid(which='minor')