python - 在 matplotlib 中绘制网格图案

标签 python matplotlib

我想用 python 和 matplotlib 画一个像下面这样的草图。我想制作网格并不难,但是如何以特定方式为某些正方形着色呢?

squares

最佳答案

N = 15
# make an empty data set
data = np.ones((N, N)) * np.nan
# fill in some fake data
for j in range(3)[::-1]:
    data[N//2 - j : N//2 + j +1, N//2 - j : N//2 + j +1] = j
# make a figure + axes
fig, ax = plt.subplots(1, 1, tight_layout=True)
# make color map
my_cmap = matplotlib.colors.ListedColormap(['r', 'g', 'b'])
# set the 'bad' values (nan) to be white and transparent
my_cmap.set_bad(color='w', alpha=0)
# draw the grid
for x in range(N + 1):
    ax.axhline(x, lw=2, color='k', zorder=5)
    ax.axvline(x, lw=2, color='k', zorder=5)
# draw the boxes
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], zorder=0)
# turn off the axis labels
ax.axis('off')

example output

关于python - 在 matplotlib 中绘制网格图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19586828/

相关文章:

python - 使用 Python 对暗淡边缘进行边缘检测

python - matplotlib 3D 散点图点的颜色非常浅

python - 将第二个图例添加到散点图

python - 为什么无法在图例旁边进行注释?

python - scipy.optimize 使用 python 解决以下等式

Python - 整理代码 - 循环和递归特性

python - (Django) 通过更新 UserProfile,图像无法正确保存

python - 如何在 IPython 中完成 win32com 代码?

python - 绘制元组列表(包含图形编号)

python - IPython 显示赋值结果