Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display numpy array in a for loop using matplotlib imshow

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

like image 493
Cecilia Avatar asked Sep 12 '14 16:09

Cecilia


People also ask

How do I show an array in matplotlib?

We can show arrays as images using the plt. imshow command from matplotlib. Here is the default output: >>> plt.

What is the difference between PLT Imshow and PLT show?

show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed. plt. imshow() draws an image on the current figure (creating a figure if there isn't a current figure).

How do I show multiple Imshow?

imshow always displays an image in the current figure. If you display two images in succession, the second image replaces the first image. To view multiple figures with imshow , use the figure command to explicitly create a new empty figure before calling imshow for the next image.


1 Answers

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:

from matplotlib.pyplot import imshow, show    

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
like image 189
rebeccaroisin Avatar answered Sep 24 '22 07:09

rebeccaroisin