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

时间:2018-10-04 06:55:38

标签: 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],
        [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()

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

1 个答案:

答案 0 :(得分:1)

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

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)

输出:

enter image description here

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