我正在尝试使用Matplotlib
和mpl_toolkits
制作3D动画。首先,我正在尝试制作不断变化的cos波的动画。但是当我运行程序时,情节是完全空的。我刚刚开始学习matplotlib
动画,因此我对此没有深入的了解。这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
line, = ax.plot([],[])
print(line)
X = np.linspace(0, 6*math.pi, 100)
def animate(frame):
line.set_data(X-frame, np.cos(X-frame))
return line
anim = animation.FuncAnimation(fig, animate, frames = 100, interval = 50)
plt.show()
答案 0 :(得分:1)
您的代码有两个问题:
set_data_3d
而不是Line3D
来更新set_data
对象的数据Axes3D
缩放比例这应该有效:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
# initialize scales
ax.set_xlim3d(0, 6 * math.pi)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(0, 100)
X = np.linspace(0, 6 * math.pi, 100)
line, = ax.plot([], [], [])
def animate(frame):
# update Line3D data
line.set_data_3d(X, np.cos(X - frame), frame)
return line,
anim = animation.FuncAnimation(fig, animate, frames = 20, interval = 50)
plt.show()
并生成类似this的动画(我已将帧数截短以减小图像文件的大小)。