I am contourplotting a matrix of data. Some of the matrix's elements are NaN's (corresponding to parameter combinations where no solution exists). I would like to indicate this region in the contourplot by a hatched region. Any idea on how to achieve this?
Asked
Active
Viewed 6,609 times
3
-
possible duplicate of [Selective patterns with Matplotlib imshow](http://stackoverflow.com/questions/14045709/selective-patterns-with-matplotlib-imshow) – tacaswell Aug 22 '13 at 21:09
1 Answers
11
contourf
and contour
methods don't draw anything where an array is masked (see here)! So, if you want the NaN elements region of the plot to be hatched, you just have to define the background of the plot as hatched.
See this example:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
# generate some data:
x,y = np.meshgrid(np.linspace(0,1),np.linspace(0,1))
z = np.ma.masked_array(x**2-y**2,mask=y>-x+1)
# plot your masked array
ax.contourf(z)
# get data you will need to create a "background patch" to your plot
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
xy = (xmin,ymin)
width = xmax - xmin
height = ymax - ymin
# create the patch and place it in the back of countourf (zorder!)
p = patches.Rectangle(xy, width, height, hatch='/', fill=None, zorder=-10)
ax.add_patch(p)
plt.show()
You'll get this figure: