3

我正在对数据矩阵进行等高线绘图。矩阵的一些元素是 NaN 的(对应于不存在解的参数组合)。我想在等高线图中用阴影区域表示这个区域。关于如何实现这一目标的任何想法?

4

1 回答 1

11

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()

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

于 2013-08-23T12:53:30.920 回答