hatch a NaN region in a contourplot in matplotlib

后端 未结 1 1191
半阙折子戏
半阙折子戏 2021-01-21 03:38

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 thi

相关标签:
1条回答
  • 2021-01-21 04:14

    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: enter image description here

    0 讨论(0)
提交回复
热议问题