为什么我的wave函数的简单动画代码不起作用?
问题描述 投票:1回答:2
我试图动画原子中电子的波函数。我在Matplotlob动画文档中给出了最简单的python代码,但它没有做任何事情。有人可以帮忙吗?
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
import math
angles = (np.linspace(0, 2 * np.pi, 360, endpoint=False))
fig= plt.figure()
ax = fig.add_subplot(111, polar=True)
line1, =ax.plot([],[], 'g-', linewidth=1)
def update(theta):
line1.set_data(angles,energy_band(3, theta, 3))
return line1,
def init():
line1.set_data([],[])
return line1,
def energy_band(wave_number, phase_offset, energy_level):
return [math.sin(2*np.pi/360*i*wave_number+phase_offset*np.pi/360)+energy_level for i in range(360)]
ani = animation.FuncAnimation(fig, update, frames=[i for i in range(0,3600,5)], blit=True, interval=200, init_func=init)
plt.show()
python
matplotlib
animation
2个回答
0
投票
问题出在您的数据上。首先,您必须使用单个数字调用set_data。其次,如果将能量函数除以100,则可以获得良好的数据显示。而且我设定了轴的极限。检查我修改代码的方式:
line1, =ax.plot([],[], 'ro')# 'g-', linewidth=1)
def update(theta):
line1.set_data(angles[int(theta)], energy_band(3, theta, 3)[int(theta)]/100)
#line1.set_data(angles,energy_band(3, theta, 3)/100)
return line1,
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
#line1.set_data([],[])
return line1,
另一件事是互动模式。当matplotlib什么都不做时,这通常是一个问题,尤其是使用jupyter笔记本。
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.interactive(True)
plt.ion()
matplotlib.is_interactive()
0
投票
问题是您要设置动画的数据介于2和4之间,但极坐标图仅显示介于-0.04和0.04之间的范围。这是因为开始使用空图。它需要您手动设置限制。例如,
ax.set_rlim(0,5)
这是代码工作所需的唯一补充。
但是,人们可能会优化一点,例如整个使用numpy并重用现有变量,
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
angles = (np.linspace(0, 2 * np.pi, 360, endpoint=False))
fig= plt.figure()
ax = fig.add_subplot(111, polar=True)
line1, =ax.plot([],[], 'g-', linewidth=1)
def update(theta):
line1.set_data(angles,energy_band(3, theta, 3))
return line1,
def init():
line1.set_data([],[])
ax.set_rlim(0,5)
return line1,
def energy_band(wave_number, phase_offset, energy_level):
return np.sin(angles*wave_number+phase_offset*np.pi/360)+energy_level
ani = animation.FuncAnimation(fig, update, frames=np.arange(0,3600,5),
blit=True, interval=200, init_func=init)
plt.show()
热门问题