移动球体动画

Moving sphere animation

我想在 matplotlib 中创建移动球体的动画。由于某种原因,它不工作:

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


fig = plt.figure(facecolor='black')
ax = plt.axes(projection = "3d")

u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(0, np.pi, 100)
r = 4

ax.set_xlim(0, 60)
ax.set_ylim(0, 60)
ax.set_zlim(0, 60)

x0 = r * np.outer(np.cos(u), np.sin(v)) + 10
y0 = r * np.outer(np.sin(u), np.sin(v)) + 10
z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50

def init():
    ax.plot_surface(x0,y0,z0)
    return fig,

def animate(i):
    ax.plot_surface(x0 + 1, y0 + 1, z0 + 1)
    return fig,

ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300)


plt.show()

在这里,我尝试在每次新的迭代中将球体移动 (1,1,1),但没有成功。

您的方法有几个错误:

  1. 在您的 animate 函数中,您在每次迭代时添加一个球体。不幸的是,Poly3DCollection 个对象(由 ax.plot_surface 创建)在创建后无法修改,因此要为表面设置动画,我们需要删除上一次迭代的表面并添加一个新的。
  2. 在您的动画中,球体没有移动,因为在每次迭代中,您都在与前一个球体相同的位置添加了一个新球体。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
from matplotlib import animation
import pandas as pd


fig = plt.figure(facecolor='black')
ax = plt.axes(projection = "3d")

u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(0, np.pi, 100)
r = 4

ax.set_xlim(0, 60)
ax.set_ylim(0, 60)
ax.set_zlim(0, 60)

x0 = r * np.outer(np.cos(u), np.sin(v)) + 10
y0 = r * np.outer(np.sin(u), np.sin(v)) + 10
z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50

surface_color = "tab:blue"

def init():
    ax.plot_surface(x0, y0, z0, color=surface_color)
    return fig,

def animate(i):
    # remove previous collections
    ax.collections.clear()
    # add the new sphere
    ax.plot_surface(x0 + i, y0 + i, z0 + i, color=surface_color)
    return fig,

ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300)


plt.show()