Python 更改网格大小以匹配网格中框的大小

Python 更改网格大小以匹配网格中框的大小,python,matplotlib,Python,Matplotlib,我正在尝试使用matplotlib制作20x20的可视化网格。但是,我在调整网格的大小以适应每个框的大小时遇到困难 这是我的密码: import matplotlib as mpl from matplotlib import pyplot import numpy as np grid = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],

我正在尝试使用matplotlib制作20x20的可视化网格。但是,我在调整网格的大小以适应每个框的大小时遇到困难

这是我的密码:

import matplotlib as mpl
from matplotlib import pyplot
import numpy as np

grid = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    ]

print (grid)

zvals = grid

# make a color map of fixed colors
cmap = mpl.colors.ListedColormap(['white','black'])
bounds=[-2,-1,1,2]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# tell imshow about color map so that only set colors are used
img = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap,norm=norm)

# make a color bar
pyplot.colorbar(img,cmap=cmap,
                norm=norm,boundaries=bounds,ticks=[0,1])

pyplot.grid(which= 'both')

pyplot.show()

我希望网格的大小为黑匣子。

您可以将此部分添加到代码中:

ax = pyplot.gca()
major_ticks = np.arange(0.5, 20, 1)
pyplolt.xticks(rotation=90)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)
ax.grid(which='both')
pyplot.grid(True)
输出:

Ps.通常以这种方式导入
pyplot
import matplotlib.pyplot as plt