gpt4 book ai didi

python - 为什么我的网格偏移量在这个例子中?

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:42 24 4
gpt4 key购买 nike

我正在尝试使用 matplotlib 绘制一个随机占用的网格。网格看起来从 block 中偏移了一个随机量:

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() 绘制轴网格。不幸的是,它不能解决问题。网格的错位是 known issue对于 imshow(由 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

关于python - 为什么我的网格偏移量在这个例子中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35214268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com