Matplotlib动画不显示任何情节

时间:2019-09-08 03:50:52

标签: python matplotlib animation

我正在尝试使用Matplotlibmpl_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() 

这是输出: enter image description here 我的代码有什么问题?为什么我没有得到任何输出?

1 个答案:

答案 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的动画(我已将帧数截短以减小图像文件的大小)。