matplotlib 三维曲面顶部的三维线动画

sxissh06  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(138)

我试图在matplotlib中的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()
iq3niunx

iq3niunx1#

1.您不会得到任何错误,因为您甚至在定义任何动画之前就调用了plt.show()。删除第一个plt.show()
1.然后你会得到预期的错误。问题是,在使用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()

相关问题