I would like to draw a sketch like the one below, using python with matplotlib. I guess making a grid is not so hard, but what about coloring certain squares in a specific way?
Asked
Active
Viewed 1.4k times
1 Answers
8
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')

tacaswell
- 84,579
- 22
- 210
- 199
-
tnx, but i get: __init__() got an unexpected keyword argument 'tight_layout' – Andrei Berceanu Oct 25 '13 at 16:15
-
@AndreiBerceanu Just remove that then. It works in newer versions of mpl – tacaswell Oct 25 '13 at 16:36
-
ok, i updated matplotlib to 1.4, and got rid of the tight_layout error. however, now it gives a warning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect. – Andrei Berceanu Oct 26 '13 at 14:46
-
weird, I don't get that. – tacaswell Oct 26 '13 at 15:15
-
This is exactly what I was looking for, but one question...how come if I set `lw=1` I lose the bottom line (x-axis) and right-most line. – Philip O'Brien Jul 16 '19 at 09:16