-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmatplotlib_3d_anim.py
89 lines (69 loc) · 2.24 KB
/
matplotlib_3d_anim.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
============
3D animation
============
A simple example of an animated plot... In 3D!
"""
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import numpy as np
def Gen_RandLine(length, dims=2):
"""
Create a line using a random walk algorithm
length is the number of points for the line.
dims is the number of dimensions the line has.
"""
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length):
# scaling the random numbers by 0.1 so
# movement is small compared to position.
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
# to allow a line to move backwards.
step = (np.random.rand(dims) - 0.5) * 0.1
lineData[:, index] = lineData[:, index - 1] + step
return lineData
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
# NOTE: there is no .set_data() for 3 dim data...
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)
# Fifty lines of random 3-D lines
data = [Gen_RandLine(25, 3) for index in range(50)]
# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel("X")
ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel("Y")
ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel("Z")
ax.set_title("3D Test")
N = 100
X = np.random.uniform(-0.1, 0.1, N)
Y = np.random.uniform(-0.1, 0.1, N)
Z = np.random.uniform(0, 0.2, N)
ax.scatter(X, Y, Z)
# Cylinder
x = np.linspace(-0.1, 0.1, 100)
z = np.linspace(0, 0.2, 100)
Xc, Zc = np.meshgrid(x, z)
Yc = np.sqrt(0.01 - Xc**2)
# Draw parameters
rstride = 20
cstride = 10
ax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)
ax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)
# Creating the Animation object
line_ani = animation.FuncAnimation(
fig, update_lines, 25, fargs=(data, lines), interval=50, blit=False
)
# line_ani.save("demo.mp4")
plt.show()