Christopher Turnbull
Christopher Turnbull

Reputation: 1003

Conditional contour plot

The below code is what I'm playing around with at the minute:

x = np.linspace(0,30,1000)
y = np.linspace(0,30,1000)
X,Y = np.meshgrid(x,y)

def f(x,y):
    return x**2 + y**2

Z = f(X,Y)


plt.contour(X, Y, Z, colors='black');

I want this plot to display some forbidden region, say when f(x,y) < 9; I want this shaded in and added to the plot. How exactly would I do this?

I've tried using plt.contourf but I can't quite get it working.

Upvotes: 0

Views: 699

Answers (1)

Scott Boston
Scott Boston

Reputation: 153510

I think you can do it this way using contourf, use contourf to fill with a solid color red then mask the region you want to display with your contour chart:

x = np.linspace(0,30,1000)
y = np.linspace(0,30,1000)
X,Y = np.meshgrid(x,y)

def f(x,y):
    return x**2 + y**2

Z = f(X,Y)

d = np.ma.array(Z, mask=Z>9)

plt.contour(X, Y, Z, colors='black')
plt.contourf(X, Y, d, colors='red');

Output:

enter image description here

Upvotes: 3

Related Questions