Skip to content

Commit 74ca427

Browse files
committed
Add previous animation examples ported to new framework, as well as a few new ones.
svn path=/trunk/matplotlib/; revision=8660
1 parent 2885eaa commit 74ca427

File tree

9 files changed

+397
-0
lines changed

9 files changed

+397
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
from animation import FuncAnimation
4+
5+
def data_gen():
6+
t = data_gen.t
7+
cnt = 0
8+
while cnt < 1000:
9+
cnt+=1
10+
t += 0.05
11+
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
12+
data_gen.t = 0
13+
14+
fig = plt.figure()
15+
ax = fig.add_subplot(111)
16+
line, = ax.plot([], [], lw=2)
17+
ax.set_ylim(-1.1, 1.1)
18+
ax.set_xlim(0, 5)
19+
ax.grid()
20+
xdata, ydata = [], []
21+
def run(data):
22+
# update the data
23+
t,y = data
24+
xdata.append(t)
25+
ydata.append(y)
26+
xmin, xmax = ax.get_xlim()
27+
28+
if t >= xmax:
29+
ax.set_xlim(xmin, 2*xmax)
30+
ax.figure.canvas.draw()
31+
line.set_data(xdata, ydata)
32+
33+
return line,
34+
35+
ani = FuncAnimation(fig, run, data_gen, blit=True, interval=10, repeat=False)
36+
plt.show()
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env python
2+
"""
3+
An animated image
4+
"""
5+
import numpy as np
6+
import matplotlib.pyplot as plt
7+
from animation import FuncAnimation
8+
9+
fig = plt.figure()
10+
11+
def f(x, y):
12+
return np.sin(x) + np.cos(y)
13+
14+
x = np.linspace(0, 2 * np.pi, 120)
15+
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
16+
17+
im = plt.imshow(f(x, y), cmap=plt.get_cmap('jet'))
18+
19+
def updatefig(*args):
20+
global x,y
21+
x += np.pi / 15.
22+
y += np.pi / 20.
23+
im.set_array(f(x,y))
24+
return im,
25+
26+
ani = FuncAnimation(fig, updatefig, interval=50, blit=True)
27+
plt.show()
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python
2+
"""
3+
An animated image
4+
"""
5+
import numpy as np
6+
import matplotlib.pyplot as plt
7+
from animation import ArtistAnimation
8+
9+
fig = plt.figure()
10+
11+
def f(x, y):
12+
return np.sin(x) + np.cos(y)
13+
14+
x = np.linspace(0, 2 * np.pi, 120)
15+
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
16+
17+
ims = []
18+
for i in range(60):
19+
x += np.pi / 15.
20+
y += np.pi / 20.
21+
ims.append([plt.imshow(f(x, y), cmap=plt.get_cmap('jet'))])
22+
23+
ani = ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
24+
plt.show()

examples/animation/histogram.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
This example shows how to use a path patch to draw a bunch of
3+
rectangles for an animated histogram
4+
"""
5+
import numpy as np
6+
7+
import matplotlib.pyplot as plt
8+
import matplotlib.patches as patches
9+
import matplotlib.path as path
10+
from animation import FuncAnimation
11+
12+
fig = plt.figure()
13+
ax = fig.add_subplot(111)
14+
15+
# histogram our data with numpy
16+
data = np.random.randn(1000)
17+
n, bins = np.histogram(data, 100)
18+
19+
# get the corners of the rectangles for the histogram
20+
left = np.array(bins[:-1])
21+
right = np.array(bins[1:])
22+
bottom = np.zeros(len(left))
23+
top = bottom + n
24+
nrects = len(left)
25+
26+
# here comes the tricky part -- we have to set up the vertex and path
27+
# codes arrays using moveto, lineto and closepoly
28+
29+
# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
30+
# CLOSEPOLY; the vert for the closepoly is ignored but we still need
31+
# it to keep the codes aligned with the vertices
32+
nverts = nrects*(1+3+1)
33+
verts = np.zeros((nverts, 2))
34+
codes = np.ones(nverts, int) * path.Path.LINETO
35+
codes[0::5] = path.Path.MOVETO
36+
codes[4::5] = path.Path.CLOSEPOLY
37+
verts[0::5,0] = left
38+
verts[0::5,1] = bottom
39+
verts[1::5,0] = left
40+
verts[1::5,1] = top
41+
verts[2::5,0] = right
42+
verts[2::5,1] = top
43+
verts[3::5,0] = right
44+
verts[3::5,1] = bottom
45+
46+
barpath = path.Path(verts, codes)
47+
patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
48+
ax.add_patch(patch)
49+
50+
ax.set_xlim(left[0], right[-1])
51+
ax.set_ylim(bottom.min(), top.max())
52+
53+
def animate(i):
54+
# simulate new data coming in
55+
data = np.random.randn(1000)
56+
n, bins = np.histogram(data, 100)
57+
top = bottom + n
58+
verts[1::5,1] = top
59+
verts[2::5,1] = top
60+
61+
ani = FuncAnimation(fig, animate, 100, repeat=False)
62+
plt.show()

examples/animation/random_data.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
from animation import FuncAnimation
4+
5+
fig = plt.figure()
6+
ax = fig.add_subplot(111)
7+
line, = ax.plot(np.random.rand(10))
8+
ax.set_ylim(0, 1)
9+
10+
def update(data):
11+
line.set_ydata(data)
12+
return line,
13+
14+
def data_gen():
15+
while True: yield np.random.rand(10)
16+
17+
ani = FuncAnimation(fig, update, data_gen, interval=100)
18+
plt.show()
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
A simple example of an animated plot... In 3D!
3+
"""
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
import mpl_toolkits.mplot3d.axes3d as p3
7+
8+
from animation import FuncAnimation
9+
10+
def Gen_RandLine(length, dims=2) :
11+
"""
12+
Create a line using a random walk algorithm
13+
14+
length is the number of points for the line.
15+
dims is the number of dimensions the line has.
16+
"""
17+
lineData = np.empty((dims, length))
18+
lineData[:, 0] = np.random.rand(1, dims)
19+
for index in xrange(1, length) :
20+
# scaling the random numbers by 0.1 so
21+
# movement is small compared to position.
22+
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
23+
# to allow a line to move backwards.
24+
step = ((np.random.rand(1, dims) - 0.5) * 0.1)
25+
lineData[:, index] = lineData[:, index-1] + step
26+
27+
return lineData
28+
29+
def update_lines(num, dataLines, lines) :
30+
for line, data in zip(lines, dataLines) :
31+
# NOTE: there is no .set_data() for 3 dim data...
32+
line.set_data(data[0:2, :num])
33+
line.set_3d_properties(data[2,:num])
34+
return lines
35+
36+
# Attaching 3D axis to the figure
37+
fig = plt.figure()
38+
ax = p3.Axes3D(fig)
39+
40+
# Fifty lines of random 3-D lines
41+
data = [Gen_RandLine(25, 3) for index in xrange(50)]
42+
43+
# Creating fifty line objects.
44+
# NOTE: Can't pass empty arrays into 3d version of plot()
45+
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
46+
47+
# Setting the axes properties
48+
ax.set_xlim3d([0.0, 1.0])
49+
ax.set_xlabel('X')
50+
51+
ax.set_ylim3d([0.0, 1.0])
52+
ax.set_ylabel('Y')
53+
54+
ax.set_zlim3d([0.0, 1.0])
55+
ax.set_zlabel('Z')
56+
57+
ax.set_title('3D Test')
58+
59+
# Creating the Animation object
60+
line_ani = FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
61+
interval=50, blit=False)
62+
63+
plt.show()

examples/animation/simple_anim.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
A simple example of an animated plot
3+
"""
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
from animation import FuncAnimation
7+
8+
fig = plt.figure()
9+
ax = fig.add_subplot(111)
10+
11+
x = np.arange(0, 2*np.pi, 0.01) # x-array
12+
line, = ax.plot(x, np.sin(x))
13+
14+
def animate(i):
15+
line.set_ydata(np.sin(x+i/10.0)) # update the data
16+
return line,
17+
18+
#Init only required for blitting to give a clean slate.
19+
def init():
20+
line.set_ydata(np.ma.array(x, mask=True))
21+
return line,
22+
23+
ani = FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
24+
interval=25, blit=True)
25+
plt.show()
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Emulate an oscilloscope. Requires the animation API introduced in
3+
matplotlib 1.0 SVN.
4+
"""
5+
import matplotlib
6+
import numpy as np
7+
from matplotlib.lines import Line2D
8+
import matplotlib.pyplot as plt
9+
from animation import FuncAnimation
10+
11+
class Scope:
12+
def __init__(self, ax, maxt=10, dt=0.01):
13+
self.ax = ax
14+
self.dt = dt
15+
self.maxt = maxt
16+
self.tdata = [0]
17+
self.ydata = [0]
18+
self.line = Line2D(self.tdata, self.ydata)
19+
self.ax.add_line(self.line)
20+
self.ax.set_ylim(-.1, 1.1)
21+
self.ax.set_xlim(0, self.maxt)
22+
23+
def update(self, y):
24+
lastt = self.tdata[-1]
25+
if lastt > self.tdata[0] + self.maxt: # reset the arrays
26+
self.tdata = [self.tdata[-1]]
27+
self.ydata = [self.ydata[-1]]
28+
self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
29+
30+
t = self.tdata[-1] + self.dt
31+
self.tdata.append(t)
32+
self.ydata.append(y)
33+
self.line.set_data(self.tdata, self.ydata)
34+
return self.line,
35+
36+
def emitter(p=0.01):
37+
'return a random value with probability p, else 0'
38+
while True:
39+
v = np.random.rand(1)
40+
if v > p:
41+
yield 0.
42+
else:
43+
yield np.random.rand(1)
44+
45+
fig = plt.figure()
46+
ax = fig.add_subplot(111)
47+
scope = Scope(ax)
48+
ani = FuncAnimation(fig, scope.update, emitter, interval=10, blit=True)
49+
plt.show()

0 commit comments

Comments
 (0)