elnino
elnino

Reputation: 173

Python plot 2D array with black and white cells

I want to plot 2D array of 1's and 0's in Python with black and white cells using pyplot.imshow(). If there is '1' then the cell color should be black and if it's '0' the cell color should be white.

I tried this:

grid = np.zeros((4, 4, 4), int)
choices = np.random.choice(grid.size, 6, replace=False)
grid.ravel()[choices] = 1

plt.imshow(grid, cmap='gray')
plt.show()

This is how the output looks like with this code

Upvotes: 1

Views: 3782

Answers (1)

Asmus
Asmus

Reputation: 5257

If you meant to create a 3-dimensional grid, than you are probably interested in plotting all slices:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(2020)

grid = np.zeros((4, 4, 4), int)
choices = np.random.choice(grid.size, 6, replace=False)
grid.ravel()[choices] = 1

print(grid)

fig,ax=plt.subplots(2,2,figsize=(6,6))
for i,a in enumerate(ax.flatten()):
    a.imshow(grid[i,:,:], cmap='gray_r',)
    a.set_title(f"slice {i}")
plt.show()

yields:

[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [1 1 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 1 0 0]
  [0 0 1 0]
  [0 0 0 0]]

 [[0 1 0 0]
  [1 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]]

and this image:

slices

If, however, you wanted to plot in 2d, then use:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(2020)

grid = np.zeros((4, 4), int)
choices = np.random.choice(grid.size, 6, replace=False)
grid.ravel()[choices] = 1

print(grid)
plt.imshow(grid,cmap='gray_r')
plt.show()

yields:

[[0 1 1 0]
 [1 0 0 0]
 [0 1 1 0]
 [1 0 0 0]]

enter image description here

Upvotes: 1

Related Questions