RubenGeert
RubenGeert

Reputation: 2952

Matplotlib fill area under curve between two x values only

I'd like to fill the area under some curve between two values on the horizontal axis only. I tried

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

x = np.linspace(-4,4, 10000)
nVals = [norm.pdf(i,0,1) for i in x]

line = plt.plot(x,nVals)

plt.fill_between(x,nVals,color = '#111111',where = x > -3 and x < -2)
plt.axis([-4,4,0,.5])
plt.show()

but it returns

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I don't understand this message; when I run

z = -2.5
print z > -3 and z < -2

Python does understand what I mean and prints

True

So why doesn't this work with fill_between and how can I solve that?

Upvotes: 2

Views: 3910

Answers (1)

tom10
tom10

Reputation: 69242

This error occurred because

x > -3 and x < -2

is an ambiguous numpy expression, so it raises the error. Instead you want

(x > -3) & (x < -2)

Other options are to use logical_and or bitwise_and (or even * should work).

Upvotes: 6

Related Questions