2016-11-08 47 views
1

从来就试图运行以下代码:的Python:发行与来自3D矩阵动画

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 
from mpl_toolkits.mplot3d import axes3d 
from matplotlib import cm #color map 

u = np.array([[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,2,0],[0,0,0]],[[0,0,0],[0,3,0],[0,0,0]]]) 
x = [-1,0,1] 
y = [-1,0,1] 
X,Y = np.meshgrid(x,y) 

fig = plt.figure() 
ax = axes3d.Axes3D(fig) 

def update(i, ax, fig): 
    ax.cla() 
    wframe = ax.plot_surface(X, Y, u[:,:,i],rstride=1,cstride=1,cmap=cm.coolwarm) 
    ax.set_zlim3d(-1,1) 
    print("step= ",i) 
    return wframe 

ani = animation.FuncAnimation(fig,update,frames=3,fargs=(ax, fig),interval=1000) 
ani.save('ani.mp4',bitrate=-1,codec="libx264") 

的动画,但是,不正常 - 它需要2倍的主要步骤(i = 0),然后,它正在循环一遍。你能帮我解决这个问题吗?

回答

0

新增init功能和repeat=False

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 
from mpl_toolkits.mplot3d import axes3d 
from matplotlib import cm #color map 

u = np.array([[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,2,0],[0,0,0]],[[0,0,0],[0,3,0],[0,0,0]]]) 
x = [-1,0,1] 
y = [-1,0,1] 
X,Y = np.meshgrid(x,y) 

fig = plt.figure() 
ax = axes3d.Axes3D(fig) 

def init(): 
    wframe = ax.plot_surface([], [], [], rstride=1, cstride=1, cmap=cm.coolwarm) 
    return wframe 

def update(i, ax, fig): 
    ax.cla() 
    wframe = ax.plot_surface(X, Y, u[:,:,i],rstride=1,cstride=1,cmap=cm.coolwarm) 
    ax.set_zlim3d(-1,1) 
    print("step= ",i) 
    return wframe 

ani = animation.FuncAnimation(fig,update,init_func=init, frames=3,fargs=(ax, fig),interval=1000,repeat=False) 
plt.show() 
+0

非常感谢您的帮助! –