Alf
Alf

Reputation: 1989

Specifying x- and y-range for a python matplotlib.pyplot contour plot

I want to make a contour plot which excludes a few coordinates, e.g. every x-coordinates that are larger then a certain threshold, let's say 9. I am not asking how to set the axes ranges, since other stuff will later we overplotted in that region with x>9.

Making the contour plot is straightforward:

import matplotlib.pyplot as plt
import numpy as np

# create x and y array
Nx = 20
Ny = 30
x = np.linspace(0,10,Nx)
y = np.linspace(0,10,Ny)

# data to plot
z = np.random.rand( Ny, Nx )

# create grid for contours
xx, yy = np.meshgrid(x, y)

fig = plt.figure( figsize=(8,6) )
ax1 = fig.add_subplot( 1,1,1 )
ax1.contourf( xx, yy, z )

plt.show()

My naive idea was to use something like

ax1.contourf( xx[np.where(xx<9)], yy[np.where(xx<9)], z[np.where(xx<9)] )

but that doesn't work due to how the indices are returned from np.where. My next approach was as follows:

ax1.contourf( xx[ np.where(xx<9)[0],np.where(xx<9)[1] ], 
              yy[ np.where(xx<9)[0],np.where(xx<9)[1] ], 
              z[  np.where(xx<9)[0],np.where(xx<9)[1] ] 
            )

Which is also not working. The error message in both cases is

TypeError: Input z must be a 2D array.

Apparently I am doing the indexing wrong. Any hint or suggestion how to do it the correct way would be greatly appreciated.

Upvotes: 1

Views: 286

Answers (1)

gehbiszumeis
gehbiszumeis

Reputation: 3711

You can do it by simply setting the corresponding values of z to np.nan. Add e.g.

cut1 = xx > 6
cut2 = yy > 2.6
cut3 = yy <= 4.1

z[cut1 & cut2 & cut3] = np.nan

before ax1.contourf(xx, yy, z) will lead to

enter image description here

Upvotes: 2

Related Questions