How use custom color mapping and vertically align images in matplotlib?

Viewed 39

Image matrix contains only 0,1,2,3 values. Can you please suggest how to:

  1. Convert: [(0, white color),(1, red color),(2, green color),(3, blue color)] when displayed using matplotlib.

  2. Align images vertically bottom.

Code:

from matplotlib import pyplot as plt
import numpy as np

img1 = np.random.randint(0, 3, (1, 4)).tolist()
img2 = np.random.randint(0, 3, (2, 4)).tolist()
img3 = np.random.randint(0, 3, (4, 4)).tolist()

fig = plt.figure()
fig.set_size_inches(10, 5)

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax0.set_aspect('equal')
ax0.axis("off")
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax1.set_aspect('equal')
ax1.axis("off")
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap='gray')
ax2.set_aspect('equal')
ax2.axis("off")
plt.gca().invert_yaxis()

plt.show()

enter image description here

1 Answers

You can use a ListedColormap for this (also, the high limit for np.random.rand is excluded, so to get numbers from 0 to 3, you should have np.random.rand(0, 4, ...). You can use ax.set_anchor('S') (for all axis) to align the plots to the bottom:

from matplotlib import pyplot as plt
import numpy as np
import matplotlib.colors

img1 = np.random.randint(0, 4, (1, 4)).tolist()
img2 = np.random.randint(0, 4, (2, 4)).tolist()
img3 = np.random.randint(0, 4, (4, 4)).tolist()

print(img1)
print(img2)
print(img3)

fig = plt.figure()
fig.set_size_inches(10, 5)

cmap = matplotlib.colors.ListedColormap(["white", "red", "green", "blue"])

ax0 = plt.subplot(1, 3, 1)
ax0.pcolor(img1, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax0.set_aspect('equal')
ax0.axis("off")
ax0.set_anchor('S')
plt.gca().invert_yaxis()

ax1 = plt.subplot(1, 3, 2)
ax1.pcolor(img2, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax1.set_aspect('equal')
ax1.axis("off")
ax1.set_anchor('S')
plt.gca().invert_yaxis()

ax2 = plt.subplot(1, 3, 3)
ax2.pcolor(img3, edgecolors='k', linewidths=2, vmin=0, vmax=4, cmap=cmap)
ax2.set_aspect('equal')
ax2.axis("off")
ax2.set_anchor('S')
plt.gca().invert_yaxis()

plt.show()

Example output:

The arrays:

[[1, 1, 2, 1]]
[[1, 2, 3, 1], [3, 1, 0, 3]]
[[0, 1, 2, 1], [0, 2, 1, 3], [0, 1, 1, 3], [3, 1, 3, 3]]

The images:

enter image description here

Related