在matplotlib中绘制网格图案

2024-05-18 23:39:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python和matplotlib绘制一个类似下面的草图。我想做一个网格并不是那么难,但是用一种特定的方式给某些正方形着色呢?

squares


Tags: 网格matplotlib方式绘制着色草图正方形
1条回答
网友
1楼 · 发布于 2024-05-18 23:39:44
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

相关问题 更多 >

    热门问题