richardbowman
richardbowman

Reputation: 131

Plotting an irregularly-spaced RGB image in Python

I want to plot several RGB images on one set of axes with matplotlib. I initially tried using imshow for this, but it doesn't seem to handle two images on one set of axes with different extents (when I plot the second, it makes the first disappear). I think the answer here is to use pcolormesh, like in How to plot an irregular spaced RGB image using python and basemap?

However, this doesn't seem to work for me - the color coming from the mappable (i.e. the data array I pass to pcolormesh, and the cmap I specify) overrides the face color I specify. The edges of the grid do have the right color, but not the faces.

Does anyone know how to set the color of the faces directly? Ideally I'd use a pcolormesh that takes an n*m*3 array as an alternative to n*m, just like imshow...

A minimal example of how I'd like it to work: import numpy as np import matplotlib.pyplot as plt

#make some sample data
x, y = np.meshgrid(np.linspace(0,255,1),np.linspace(0,255,1))
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,120))
b=255-r

#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T

m = plt.pcolormesh(x, y, rgb/255.0, linewidth=0)
plt.show()

The problem is that the call to plt.pcolormesh fails, with

numRows, numCols = C.shape
ValueError: too many values to unpack

I guess this is because it wants a 2D array, not a 3D array with the last dimension being 3 long.

Upvotes: 4

Views: 3240

Answers (2)

Dennis Sakva
Dennis Sakva

Reputation: 1467

How about combining all your images into one big numpy array which you then display with imshow?

Upvotes: -3

richardbowman
richardbowman

Reputation: 131

The solution was very simple: the one thing I needed to do that wasn't in the question I linked to was to remove the array from the mesh object. A minimal example, in case it's helpful to others:

import numpy as np
import matplotlib.pyplot as plt

#make some sample data
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,100))
b=255-r

#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T

color_tuple = rgb.transpose((1,0,2)).reshape((rgb.shape[0]*rgb.shape[1],rgb.shape[2]))/255.0

m = plt.pcolormesh(r, color=color_tuple, linewidth=0)
m.set_array(None)
plt.show()

I guess the color_tuple line might be non-obvious: essentially we need to turn the (n, m, 3) array into an (n*m, 3) array. I think the transpose is necessary to get everything to match up correctly. It's also worth noting that the colors we pass in need to be floating-point, between 0 and 1.

Upvotes: 9

Related Questions