繁体   English   中英

用于 3D 表面上的 3D 线动画的 Matplotlib 代码

[英]Matplotlib code for 3D line animation on top of a 3D surface

我正在尝试在 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. 您不会收到任何错误,因为您在定义任何动画之前调用了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()

暂无
暂无

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

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