Matplotlib的matshow不与网格对齐

luf*_*ffe 5 python numpy matplotlib

我有一个代表网格的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.]])
Run Code Online (Sandbox Code Playgroud)

我想绘制这个,但是matplotlib错了,你可以在下面看到.红色正方形应该覆盖水平轴和垂直轴上从0到3的区域.

In [88]:

plt.matshow(arr)
plt.grid()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我该如何解决?谢谢

jed*_*rds 8

您可以使用主要刻度标记和网格的小刻度.

考虑:

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()
Run Code Online (Sandbox Code Playgroud)

这表现了:

产量

诀窍就是这两行:

plt.gca().set_xticks(..., minor='true')
plt.grid(which='minor')
Run Code Online (Sandbox Code Playgroud)


mdu*_*ant 4

如果您愿意,您可以使用:

matshow(arr, extent=[0, 6, 0, 6])
Run Code Online (Sandbox Code Playgroud)

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