Matplotlib代码,用于在3D表面上进行3D线动画

时间:2019-01-27 19:54:30

标签: python matplotlib

我正在尝试在matplotlib中的3D表面图上创建3D线动画。

我能够绘制3D曲面,但是没有动画。而且代码中没有错误。我正在将3D线的X,Y和Z值设置为当前帧。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import animation

def f(x,y):
    return x+y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(0, 10, 1)
Y = np.arange(0, 10, 1)
Z = X+Y

X1, Y1 = np.meshgrid(X, Y)
Z1 = f(X1, Y1)
ax.plot_surface(X1, Y1, Z1, color='b', alpha=0.5)
plt.show()

line, = ax.plot([], [], [], lw=2)
def init():
    line.set_data([], [])
    line.set_3d_properties([])
    return line
def animate(i, line, X, Y, Z):
    line.set_data(X[:i], Y[:i])
    line.set_3d_properties(Z[:i])
    return line
anim = animation.FuncAnimation(fig, animate, init_func=init, fargs=(line, X, Y, Z),
                           frames=10, interval=200,
                           repeat_delay=5, blit=True)
plt.show()

1 个答案:

答案 0 :(得分:0)

  1. 您没有得到任何错误,因为您甚至在定义任何动画之前就调用plt.show()。删除第一个plt.show()
  2. 然后您将得到预期的错误。问题是使用blit=True时需要从动画功能返回艺术家列表。只需添加逗号

    即可轻松实现
     return line, 
    

完整代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import animation

def f(x,y):
    return x+y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(0, 10, 1)
Y = np.arange(0, 10, 1)
Z = X+Y

X1, Y1 = np.meshgrid(X, Y)
Z1 = f(X1, Y1)
ax.plot_surface(X1, Y1, Z1, color='red', alpha=0.5)

line, = ax.plot([], [], [], lw=2)

def init():
    line.set_data([], [])
    line.set_3d_properties([])
    return line,

def animate(i, line, X, Y, Z):
    line.set_data(X[:i], Y[:i])
    line.set_3d_properties(Z[:i])
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init, fargs=(line, X, Y, Z),
                           frames=10, interval=200,
                           repeat_delay=5, blit=True)
plt.show()