ValientProcess
ValientProcess

Reputation: 1801

Shade area between 2 y coordinates in matplotlib

I'm trying to create a shaded rectangle based on two vertical coordinates (the length of the rectangle should span the whole x axis). I've tried to use fill_between with the following (p1 & p2 are the data coordinates):

f, ax1 = plt.subplots()   
x = np.linspace(200,300,2000)
y = x**(2)
y1 = x
p1 = 4700
p2 = 7700

ax1.plot(x, y, lw=2)
ax1.set_xlabel('Temperature $[K]$', fontweight='bold')
ax1.set_ylabel('Pressure $[mb]$', fontweight='bold')
ax1.fill_between(x, y1.fill(p1), y1.fill(p2))

But i'm getting the following error:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

What is wrong? Any better way to do this?

Thank you!!

Upvotes: 1

Views: 712

Answers (4)

sacuL
sacuL

Reputation: 51335

IIUC, the issue is with the use of the .fill() function. You can avoid that, using fill_between with your x array and just the p1 and p2 values, as fill_between can accept scalar values for y1 and y2.

ax1.fill_between(x, p1, p2)

enter image description here

Note, you can change the color and transparancy easily by adding a color and alpha argument:

ax1.fill_between(x, p1, p2, color='limegreen', alpha=0.5)

Upvotes: 1

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

The fill method of an array doesn't return an array, it returns None.

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339170

Possibly you mean to use axhspan.

p1 = 4700
p2 = 7700
ax1.axhspan(p1, p2, color="limegreen", alpha=0.5)

enter image description here

Upvotes: 3

Paula Thomas
Paula Thomas

Reputation: 1190

You've misunderstood fill_between. When you use it is advisable to express y as a function:

def y(x):
    return x**2
section = np.arange(start,end,0.1)
plt.fill_between(section,y(section))

will do the job with suitable values for start and end.

Upvotes: -2

Related Questions