用于 3D 表面上的 3D 线动画的 Matplotlib 代码 [英] Matplotlib code for 3D line animation on top of a 3D surface
本文介绍了用于 3D 表面上的 3D 线动画的 Matplotlib 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在matplotlib中的3D表面图的顶部创建3D线动画.
I am trying to create a 3D line animation, on top of a 3D surface plot in matplotlib.
我能够绘制 3D 表面,但没有动画.并且代码中没有错误.我正在将3D线的X,Y和Z值设置为当前帧.
I am able to plot the 3D surface, but there is no animation. And there is no error in the code. I am setting the X,Y and Z values of the 3D line upto the current frame.
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()
推荐答案
- 您没有得到任何错误,因为您甚至在定义任何动画之前就调用了
plt.show()
.删除第一个plt.show()
. 然后你会得到预期的错误.问题是当使用
blit=True
时,您需要从动画函数返回艺术家列表.这很容易通过添加逗号来实现,
- You don't get any error, because you call
plt.show()
before any animation is even defined. Remove the firstplt.show()
. You will then get errors as expected. The problem is that you need to return a list of artists from the animating functions when using
blit=True
. This is easily achieved by adding a comma,
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()
这篇关于用于 3D 表面上的 3D 线动画的 Matplotlib 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文