简体   繁体   English

Matplotlib动画不显示任何情节

[英]Matplotlib animation not showing any plot

I am trying to make an animation in 3D using Matplotlib and mpl_toolkits . 我正在尝试使用Matplotlibmpl_toolkits制作3D动画。 For starter, I am trying to make an animation of a shifting cos wave. 首先,我正在尝试制作不断变化的cos波的动画。 But when I run the program, the plot is completely empty. 但是当我运行程序时,情节是完全空的。 I have just started learning matplotlib animations, so I don't have in-depth knowledge of it. 我刚刚开始学习matplotlib动画,所以我对此没有深入的了解。 Here is my code: 这是我的代码:

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() 

Here is the output: 这是输出: 在此处输入图片说明 What is wrong with my code? 我的代码有什么问题? Why am I not getting any output? 为什么我没有得到任何输出?

There are two issues with your code: 您的代码有两个问题:

  • use set_data_3d to update the data of a Line3D object instead of set_data 使用set_data_3d而不是set_data更新Line3D对象的数据
  • initialize the Axes3D scales before starting the animation 在开始动画之前初始化Axes3D比例

This should work: 这应该工作:

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()

and yield an animation like this (I have truncated the number of frames to reduce image file size). 并产生像的动画这个 (我截断的帧的数量,以减少图像文件大小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM