Reputation: 3961
I'm trying to generate and plot random numbers using:
from numpy import random
import matplotlib.pyplot as plt
z = 15 + 2*random.randn(200) #200 elements, normal dist with mean = 15, sd = 2
plt.plot(z)
plt.show(z)
The graph is plotted, but Python (2.7.5) freezes and I get the error
Traceback (most recent call last):
File "G:\Stage 2 expt\e298\q1.py", line 25, in <module>
plt.show(z)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 145, in show
_show(*args, **kw)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 90, in __call__
if block:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
It's completely fine when I do a for loop like so:
from numpy import random
from pylab import plot,show
yvec = [] # set up an empty vector
for i in range(200): # want 200 numbers
yy = 25 + 3*random.randn() # normal dist with mean = 15, sd = 2
yvec.append(yy) # enter yy into vector
plot(yvec)
show(yvec)
Could someone please clarify?
Upvotes: 2
Views: 11519
Reputation: 8487
The function pylab.show
does not take a list or array, it takes an optional boolean (and certainly not your data array). The numpy array in the first example can't be implicitly converted to a boolean, thus throwing an error. The second one can however be converted to a boolean, and it will evaluate to True
if non-empty.
To fix it, just call show
without any arguments.
Upvotes: 5