Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a numpy array whose elements are updated in a for loop:

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

for t in range(0,10):
    imshow(a)

    for i in range(0,a.shape[0]):
        for j in range(0,a.shape[1]):
            a[i][j] += 1

I want to display the array at each iteration, but imshow() doesn't work, it just displays the image once the loop terminates.

ps. I'm using an Ipython notebook

I found different things on the web but none of them work on my computer (for example I tried to use matplotlib's animation module)

The strange thing is that if I try to execute this example (http://matplotlib.org/examples/animation/dynamic_image2.html) using the standard python prompt everything works fine, while on the Ipython notebook it doesn't work. Can anyone explain me why?

notes:

Maybe I oversimplified my code;

I'm working on a forest-fire model, the array is a grid filled with 0 = empty site, 1 = tree, 2 = fire.

At each time step (iteration):

  1. a tree is dropped on a randomly chosen site and if the site is free the tree is planted
  2. a tree ignites with a probability f

I want to display the array using a colormap to visualize the evolution of my model

share|improve this question
    
Just a side note, why don't you do something like a += np.ones(a.shape)? –  robbrit 2 days ago
    
Yes, I can do that, but I wrote down this array and this for loop just to explain my problem. This isn't the actual code I'm working on :) –  Cecilia 2 days ago

2 Answers 2

up vote 2 down vote accepted

imshow(a) will plot the values of the array a as pixel values, but it won't display the plot. To view the image after each iteration of the for loop, you need to add show().

This should do what you want:

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

for t in range(0,10):
    imshow(a)
    show()

    for i in range(0,a.shape[0]):
        for j in range(0,a.shape[1]):
            a[i][j] += 1
share|improve this answer

imshow is for showing images in a plot. Use print to show a numpy array:

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

for t in range(0,10):
    print a

    # ...
share|improve this answer
    
Thank you, but I want a visual representation of the array, with colorbar() etc. In the real code each array element has its color. Maybe I oversimplified my code. –  Cecilia 2 days ago
1  
Yeah you'll need clarify how the array is supposed to be displayed. –  robbrit 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.