How to pcolormesh RGBA array with 2D x and y?

Viewed 249

I have a RGBA array (img) with 2D x and y like this:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(100)

x = np.arange(10, 20)
y = np.arange(0, 10)
x, y = np.meshgrid(x, y)

img = np.random.randint(low=0, high=255, size=(10, 10, 4))

According to this question, we can pass any array to plot and set the color using img:

fig, axs = plt.subplots()
axs.pcolormesh(x, y, img[:, :,0], color=img.reshape((img.shape[0]*img.shape[1]), 4)/255)

However, it just changed the edgecolors.

edge_color

I want to show it like axs.imshow(img)

imshow

1 Answers

Update: here is the completed example code given the trick you found to impede the assignment of the colormapped colors.

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(100)

x = np.arange(10, 21)
y = np.arange(0, 11)
x, y = np.meshgrid(x, y)

img = np.random.randint(low=0, high=255, size=(10, 10, 4))

fig, ax = plt.subplots()
mesh = ax.pcolormesh(x, y, img[:, :,0], facecolors=img.reshape(-1, 4)/255)
# This is necessary to let the `color` argument determine the color
mesh.set_array(None)
plt.show()

pcolormesh with changed colors

PS: Also note that img.reshape(-1, 4) is a shortcut (and more maintainable) version of img.reshape(img.shape[0]*img.shape[1], 4).

Also note that the x and y refer to the borders between the cells, and there need to be one value more than the number of cells in each dimension. Therefore, I incremented np.arange(10, 20) to np.arange(10, 21), but if you want 10..19 as centers, you need to subtract 0.5 for the position of the border (as e.g. np.arange(10, 21) - 0.5).

As commented by Jody Klymak, it's recommended not to use color which refers to both facecolor and edgecolor. As the edges are overlapping with their neighbors, some strange effects are visible when transparency comes into play.

Related