0

I am wondering what's the best approach to turn a large number of images into a moving one in Python. A lot of examples I've found seem to deal with actual videos or video games, such as pygame, which seems over complicated for what I'm looking to do.

I have created a loop, and would like the image to update every time the code runs through the loop. Is there a possibly a method in python to overplot each image and erase the previous image with each iteration?

sweeps_no = 10
for t in range(sweeps_no):

    i = np.random.randint(N)
    j = np.random.randint(N)

    arr = nearestneighbours(lat, N, i, j)
    energy = delta_E(lat[i,j], arr, J)
    if energy <= 0:
        matrix[i,j] *= matrix[i,j]
    elif np.exp(energy/T) >= np.random.random():
        matrix[i,j] *= -matrix[i,j]
    else:
        matrix[i,j] = matrix[i,j]
    t +=1
    print t
    res.append(switch)
    image = plt.imshow(lat)
    plt.show()

Also, I can't understand why the loop above doesn't result in 10 different images showing up when the image is contained in the loop.

Chris Lee
  • 59
  • 1
  • 7
  • Each iteration you are drawing on the same figure. If you want 10 images, you have to create 10 figures (and if you want them all to show up at the end of the script, move `plt.show()` outside of the loop) – DavidG Jan 09 '18 at 12:20
  • Thanks a lot. I was wondering why I wasn't hit with a tonne of images all at once when I ran the code – Chris Lee Jan 09 '18 at 12:22
  • Possible duplicate of [Programmatically generate video or animated GIF in Python?](https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python) – Peter Wood Jan 09 '18 at 12:26
  • Do you want to keep updating one single figure? And for each iteration re-draw the result of `imshow`? – DavidG Jan 09 '18 at 12:27
  • Yes I would @DavidG, I am trying to show how it changes with time – Chris Lee Jan 09 '18 at 13:47

1 Answers1

1

You can update a single figure using fig.canvas.draw() after your call to imshow(). It is important to include a pause i.e. plt.pause(2), so that you can see the changes to your figure.

The following is a runnable example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()  # create the figure

for i in range(10):

    data = np.random.randn(25).reshape(5,5)  # some fake data

    plt.imshow(data)

    fig.canvas.draw()
    plt.pause(2)   # pause for 2 seconds
DavidG
  • 24,279
  • 14
  • 89
  • 82