2

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?

1
  • 1
    The difference is in the list type: The explicit for loop uses python's builtin list, while random.randn will return a numpy array. Commented Jan 29, 2014 at 2:11

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.