|
| 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() |
0 commit comments