在matplotlib的contourplot中孵化NaN区域

Mat*_*hem 3 matplotlib nan contour

我正在绘制一个数据矩阵.一些矩阵的元素是NaN(对应于没有解的存在的参数组合).我想用阴影区域在等高线图中指出这个区域.有关如何实现这一点的任何想法?

car*_*rla 9

contourfcontour方法不会绘制数组被掩盖的任何东西(见这里)!因此,如果您想要绘制阴影的NaN元素区域,则只需将阴影的背景定义为阴影.

看这个例子:

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()
Run Code Online (Sandbox Code Playgroud)

你会得到这个数字: 在此输入图像描述