hatch a NaN region in a contourplot in matplotlib

我们两清 提交于 2019-12-20 02:17:51

问题


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?


回答1:


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.

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:



来源:https://stackoverflow.com/questions/18390068/hatch-a-nan-region-in-a-contourplot-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!