Search code examples
pythonmatplotlibmaskcontour

Masked contour plot in python without filler between True-False


I would like to draw a single contourline from a masked array.

The problem is matplotlib draws several lines in the "unknown" area between True and False and not a single line.

It doesn't matter if the line is in the middle or on the edge of True or False, so in the simple example below, I would like a single line in either Y=1, Y=2 or Y=1.5.

X = np.array([1,2,3,4,5])

Y = np.array([0,1,2,3])

Z_mask = np.array([[False, False, False, False, False],
                   [False, False, False, False, False],
                   [True, True, True, True, True],
                   [True, True, True, True, True]])

plt.contour(X,Y,Z_mask)           

plt.show() 

Image plot example
Image plot example

I have tried the different keyword arguments for plt.contour but none of them seems to do the job.


Solution

  • You can tell contour how many levels to plot using a forth argument:

    From the docs:

    contour(X,Y,Z,N)

    contour up to N automatically-chosen levels.

    So for your plot:

    plt.contour(X,Y,Z_mask,1)           
    

    Produces:

    enter image description here


    Sidenote: For your 'workaround' in your comment above, there is no need to convert your mask array from False and True to 0 and 1, as in python, booleans are just a subclass of integers:

    In [14]: False == 0
    Out[14]: True
    
    In [15]: True == 1
    Out[15]: True