matplotlib 3D散布动画不打印点

jqjz2hbq  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(94)

我重用了一段代码,它可以在2D动画中工作,但我不能调整它在3D中工作,它只是绘制第一个点,什么也不做。

def func(x, y):
    return np.cos(x)*np.sin(y)
fig = plt.figure(figsize=(4,4))
fig.tight_layout()
x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, np.pi, 100)
X, Y = np.meshgrid(x, y)
Z = func(X, Y)
# 
ax = Axes3D(fig, computed_zorder=False)
ax.plot_surface(X, Y, Z, cmap="coolwarm", alpha=0.6)
x_ticks = [0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]
x_labels = ["0", "π/2", "π", "3π/2", "2π"]
y_ticks = [0, np.pi/2, np.pi]
y_labels = ["0", "π/2", "π"]
z_ticks = [0, 1, 0, -1, 0]
z_labels = ["0", "1", "0", "-1", "0"]
ax.set_xticks(x_ticks, x_labels)
ax.set_yticks(y_ticks, y_labels)
ax.set_zticks(z_ticks, z_labels)
ax.set_title("cos(x)*sin(y)")
ax.grid(False)
# Gradiente
paso = 1
x_Coord = [0.4*np.pi]
y_Coord = [0.2*np.pi]
z_Coord = [func(x_Coord[0], y_Coord[0])]
gradF = [-0.5590, 0.25, func(-0.5590, 0.25)]
for n in range(3):
    x_Coord.append(x_Coord[n] + paso*(gradF[0]))
    y_Coord.append(y_Coord[n] + paso*(gradF[1]))
    z_Coord.append(z_Coord[n] + paso*(gradF[2]))
#GIF
scat_1 = ax.scatter(x_Coord[0], y_Coord[0], z_Coord[0], c="black", s=50)
def animate(i):
    scat_1.set_offsets((x_Coord[i], y_Coord[i], z_Coord[i]))
    return scat_1
ani = animation.FuncAnimation(fig, animate, frames=len(z_Coord))
writer = animation.PillowWriter(fps=1)
ani.save("Imagenes/gradiente1.gif", writer=writer)
plt.show()

字符串
我的gif看起来像这样:

的数据
但它应该看起来像这个

ymzxtsji

ymzxtsji1#

对于3D散点图动画,需要使用Axe._offsets3d = (x,y,z)。由于某些原因(与后端出于性能原因对变量进行排序有关),xyz不能是浮点数,因此我们将传递x_Coord[i:i+1],而不是传递x_Coord[i],以便它可以是一个numpy数组。
所以,你的animate函数现在应该是:

def animate(i):
    scat_1._offsets3d = (x_Coord[i:i+1], y_Coord[i:i+1], z_Coord[i:i+1])
    return scat_1

字符串


的数据

相关问题