CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download
Project: test
Views: 91872
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Sun Sep 14 12:41:24 2014
4
5
@author: rlabbe
6
"""
7
8
from matplotlib import animation
9
import matplotlib.pyplot as plt
10
11
def animate(filename, func, frames, interval, fig=None, figsize=(6.5, 6.5)):
12
""" Creates an animated GIF of a matplotlib.
13
14
Parameters
15
----------
16
filename : string
17
name of the file. E.g 'foo.GIF' or '\home\monty\parrots\fjords.gif'
18
19
func : function
20
function that will be called once per frame. Must have signature of
21
def fun_name(frame_num)
22
23
frames : int
24
number of frames to animate. The current frame number will be passed
25
into func at each call.
26
27
interval : float
28
Milliseconds to pause on each frame in the animation. E.g. 500 for half
29
a second.
30
31
figsize : (float, float) optional
32
size of the figure in inches. Defaults to 6.5" by 6.5"
33
"""
34
35
36
37
def forward(frame):
38
# I don't know if it is a bug or what, but FuncAnimation calls twice
39
# with the first frame number. That breaks any animation that uses
40
# the frame number in computations
41
if forward.first:
42
forward.first = False
43
return
44
func(frame)
45
46
if fig is None:
47
fig = plt.figure(figsize=figsize)
48
forward.first = True
49
anim = animation.FuncAnimation(fig, forward, frames=frames, interval=interval)
50
anim.save(filename, writer='imagemagick')
51