我试图用matplotlib绘制一个随机占用的网格。网格看起来与块的偏移量是随机的:
以下是代码:
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的新手。
答案 0 :(得分:3)
您可以使用plt.grid()
绘制轴网格。不幸的是,它不会解决问题。对于imshow
(由matshow
调用的函数),网格的未对齐为known issue。
我建议使用数字大小和网格的线宽,直到你得到可接受的东西。
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)
答案 1 :(得分:1)
这是known behavior,因为默认情况下,matshow()
使用参数imshow()
调用interpolation="nearest"
。通过手动覆盖参数,您应该获得更好的结果:
plt.matshow(image, cmap='Greys', interpolation="none")