在matplotlib中的轮廓图中填充NaN区域 [英] hatch a NaN region in a contourplot in matplotlib

查看:73
本文介绍了在matplotlib中的轮廓图中填充NaN区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

contourfcontour方法不会在屏蔽数组的地方绘制任何内容(请参见

contourf and contourmethods 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.

请参见以下示例:

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:

这篇关于在matplotlib中的轮廓图中填充NaN区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆