我正在绘制数据矩阵的轮廓图。该矩阵的一些元素是NaN(对应于不存在解的参数组合)。我想通过阴影区域在轮廓图中指示此区域。有什么方法可以实现?
我正在绘制数据矩阵的轮廓图。该矩阵的一些元素是NaN(对应于不存在解的参数组合)。我想通过阴影区域在轮廓图中指示此区域。有什么方法可以实现?
contourf
和contour
方法在数组被掩码时不会绘制任何内容(参见此处)!因此,如果您想要绘图的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()