Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pcolormesh with missing values?

I have 3 1-D ndarrays: x, y, z

and the following code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as spinterp

## define data
npoints = 50
xreg = np.linspace(x.min(),x.max(),npoints)
yreg = np.linspace(y.min(),y.max(),npoints)
X,Y = np.meshgrid(xreg,yreg)
Z = spinterp.griddata(np.vstack((x,y)).T,z,(X,Y),
                      method='linear').reshape(X.shape)

## plot
plt.close()
ax = plt.axes()
col = ax.pcolormesh(X,Y,Z.T)
plt.draw()

My plot comes out blank, and I suspect it is because the method='linear' interpolation comes out with nans. I've tried converting to a masked array, but to no avail - plot is still blank. Can you tell me what I am doing wrong? Thanks.

like image 959
hatmatrix Avatar asked Oct 15 '11 14:10

hatmatrix


People also ask

What is Matplotlib pcolormesh in Python?

In this article, we will be learning about Matplotlib pcolormesh in Python. The Matplotlib library in Python is numerical for NumPy library. Pyplot is a library in Matplotlib, which is basically a state-based interface that provides MATLAB-like features .

What is the difference between pcolor and pcolormesh?

Use pcolor if you need this functionality. Both methods are used to create a pseudocolor plot of a 2D array using quadrilaterals. The main difference lies in the created object and internal data handling: While pcolor returns a PolyCollection, pcolormesh returns a QuadMesh. The latter is more specialized for the given purpose and thus is faster.

Why does pcolormesh not support X and Y arrays?

However, only pcolor supports masked arrays for X and Y. The reason lies in the internal handling of the masked values. pcolor leaves out the respective polygons from the PolyCollection. pcolormesh sets the facecolor of the masked elements to transparent. You can see the difference when using edgecolors.

Is it possible to change the shading in pcolormesh?

We learned about pcolormesh in Matplolib and also saw its various examples. The shading can also be changed as one requires. However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.


1 Answers

Got it. This seems round-about, but this was the solution:

import numpy.ma as ma

Zm = ma.masked_where(np.isnan(Z),Z)
plt.pcolormesh(X,Y,Zm.T)

If the Z matrix contains nan's, it has to be a masked array for pcolormesh, which has to be created with ma.masked_where, or, alternatively,

Zm = ma.array(Z,mask=np.isnan(Z))
like image 102
hatmatrix Avatar answered Oct 11 '22 13:10

hatmatrix