GIF animation in Matlab in 3 steps is a popular post here on this blog. Learnt the technique while trying to plot the results from the Karhunen-Loeve Expansion in September 2012.
Since then, I have moved from matlab to python.
But I wanted to recreate that same thing in Python. This is where I have to say, Matlab is like iOS and Python is Android. For doing this in Matlab, all ingredients were in place, but in python, this isn’t the case.
So here are the 3 long steps in Python to get a GIF animation.
Step 1:
Download Figtodat and images2gif
Step 2:
Import Figtodat and writeGif
import Figtodat from images2gif import writeGif
Step 3:
Collect the figures into an array and call writeGif to get the animation
figure = plt.figure() plot = figure.add_subplot (111) plot.hold(False) images=[] y = numpy.random.randn(100,5) for i in range(y.shape[1]): plot.plot (numpy.sin(y[:,i])) im = Figtodat.fig2img(figure) images.append(im) writeGif("images.gif",images,duration=0.3,dither=0)
Don’t want to spend time finding the listed modules, download them directly from the link at the end of the post.
Here’s the complete code.
# -*- coding: utf-8 -*- """ @author: Sukhbinder Singh """ import Figtodat from images2gif import writeGif import matplotlib.pyplot as plt import numpy figure = plt.figure() plot = figure.add_subplot (111) plot.hold(False) # draw a cardinal sine plot images=[] y = numpy.random.randn(100,5) for i in range(y.shape[1]): plot.plot (numpy.sin(y[:,i])) plot.set_ylim(-3.0,3) plot.text(90,-2.5,str(i)) im = Figtodat.fig2img(figure) images.append(im) writeGif("images.gif",images,duration=0.3,dither=0)
Leave a comment