0

This code, plots a normal distribution curve:

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

plt.rc('text', usetex=True)

x = np.arange(-6, 6, 0.1)

distrib_1 = norm(0, 1) 
y_distrib_1 = distrib_1.pdf(x)

fig = plt.figure(figsize=(12, 8)) 

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])

axes.plot(x, y_distrib_1, color='red', linewidth=2, label=r'Normal distribution: $\mu = 0, \sigma = 1$')

axes.set_xlabel('x')
axes.set_ylabel('P(x)')
axes.set_title('The Normal Distribution')
axes.grid(True)
axes.legend(loc=2);
plt.show()

Now I want to fill the range between x=-1 and x=1. What I tried to do is axes.fill_between(x, y_distrib_1, 0, where = -1<x<1) but then I get the error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() at that line.

I tried axes.fill_between(x, y_distrib_1, 0, where = (-1<x and x<1), color='red') and it also didn't work.

What I can do is:

p = [(True if -1<val and val<1 else False) for val in x]
axes.fill_between(x, y_distrib_1, 0, where = p)

that works, but this code feels quite ugly.

What to do? I didn't find any similar example in the matplotlib documentation.

Renan
  • 462
  • 7
  • 24
  • possible duplicate of [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](http://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – Michael Foukarakis Jan 01 '14 at 21:24

2 Answers2

1

You were close, this will work:
axes.fill_between(x, y_distrib_1, 0, where = (-1<x) & (x<1))

M4rtini
  • 13,186
  • 4
  • 35
  • 42
-1

It should be something like

fill_between(y_distrib_1, 0, where = (-1<x&&x<1)). 

Remember, most languages cannot parse things like -1<x<1. Even though that is a perfectly sound mathematical idea, the way most code sees it is like this:

is -1 < x? Yes? Ok, the statement -1 < x is now TRUE.
is TRUE<1? TRUE in python is 1, so is 1<1, no, FALSE.

The code won't test x against both -1 and 1, you have to break it up and put an "and" (&&) in.

Edit: looking at the actual way to use fill_between, it looks like you should do this

fill_between(y_distrib_1,-1, 1)
Damien Black
  • 5,579
  • 18
  • 24