使用 Matplotlib 的氢原子 3D 动画

3D Animation of hydrogen atom using Matplotlib

我想制作氢原子轨道的 3D 动画。因此我创建了以下程序:

#Repositorys
import numpy as np
from scipy.special import sph_harm
import matplotlib.pyplot as plt
import matplotlib as matplotlib
from mpl_toolkits.mplot3d import Axes3D
import cmath


#Create Diagramm
fig = plt.figure(figsize = (10,10))
ax = fig.add_subplot(111, projection='3d')

#Variables
l = 0
m = 0
phi = np.linspace(0, np.pi , 150)
theta = phi = np.linspace(0, 2*np.pi , 150)

#Variables for linear combination
l2 = 1
m2 = 0
t = 0

#Calculate  linear combination
X = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j))  * np.outer(np.cos(phi), np.sin(theta))
Y = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j)) * np.outer(np.sin(phi), np.sin(theta))
Z = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j)) * np.outer(np.ones(np.size(phi)), np.cos(theta))

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, color='b')

plt.show()

现在我想制作动画,当时间 t 从 0 运行到 2*pi 时对象如何变化。我怎样才能使用 matplotlib 做到这一点?我试图在教程的帮助下做到这一点,但感到困惑。感谢您的支持。

PS:如果有人知道如何用搅拌机渲染这个...你就是我的英雄

使用 matplotlib.animation.FuncAnimation -

这非常简单
import numpy as np
from scipy.special import sph_harm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
import cmath

fig = plt.figure(figsize = (7,7))
ax = fig.add_subplot(111, projection='3d')

l = 0
m = 0
l2 = 1
m2 = 0
phi = np.linspace(0, np.pi , 150)
theta = phi = np.linspace(0, 2*np.pi , 150)

surf = ax.plot_surface(np.array([[]]), np.array([[]]), np.array([[]]))
ax.set_xlim([-0.75, 0.75])
ax.set_ylim([-0.75, 0.75])
ax.set_zlim([-0.75, 0.75])

def animate(i):
    global surf
    t = 2 * np.pi / nframes * i;
    X = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j)) \  
        * np.outer(np.cos(phi), np.sin(theta))
    Y = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j)) \
        * np.outer(np.sin(phi), np.sin(theta))
    Z = abs(sph_harm(m, l, theta, phi)  + sph_harm(m2, l2, theta, phi) * cmath.exp(-t*1j)) \
        * np.outer(np.ones(np.size(phi)), np.cos(theta))

    surf.remove()
    fig.canvas.draw()
    surf = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, color='b')

nframes = 36
anim = FuncAnimation(fig, animate, frames=nframes+1, interval=2000/(nframes+1))

您可以根据需要缩放帧数,interval 指定帧之间的间隔(以毫秒为单位)- 我在这里缩放它以便动画始终长 2 秒: