python-为什么在此示例中我的网格偏移量?

我正在尝试使用matplotlib绘制一个随机占用的网格.网格看起来与块之间的偏移量是随机的:

The grid

这是代码:

import matplotlib.pyplot as plt
import numpy as np

# Make a 10x10 grid...
nrows, ncols = 10,10
# Fill the cells randomly with 0s and 1s
image = np.random.randint(2, size = (nrows, ncols))

# Make grid
vgrid = []
for i in range(nrows + 1):
    vgrid.append((i - 0.5, i - 0.5))
    vgrid.append((- 0.5, 9.5))

hgrid = []
for i in range(ncols + 1):
    hgrid.append((- 0.5, 9.5))
    hgrid.append((i - 0.5, i - 0.5))

row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'j']

plt.matshow(image, cmap='Greys')
for i in range(11):
    plt.plot(hgrid[2 * i], hgrid[2 * i + 1], 'k-')
    plt.plot(vgrid[2 * i], vgrid[2 * i + 1], 'k-')

plt.axis([-0.5, 9.5, -0.5, 9.5])
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels)

plt.show()

当我强制执行一个绘图区域时,似乎出现了问题.这行:

plt.axis([-0.5, 9.5, -0.5, 9.5])

另外,请随时提出更好的方法.我是pyplot的新手.

最佳答案

您可以使用plt.grid()绘制轴网格.不幸的是,它无法解决问题.网格的未对齐是imshow的known issue(matshow调用的函数).

我建议您使用图形的大小和网格的线宽,直到您可以接受为止.

plt.figure(figsize=(5,5));

nrows, ncols = 10,10
image = np.random.randint(2, size = (nrows, ncols))
row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'j']
plt.matshow(image, cmap='Greys',fignum=1,interpolation="nearest")

#set x and y ticks and labels
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels);

#set minor axes in between the labels
ax=plt.gca()
ax.set_xticks([x-0.5 for x in range(1,ncols)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,nrows)],minor=True)
#plot grid on minor axes
plt.grid(which="minor",ls="-",lw=2)

enter image description here