我正在尝试使原子中电子的波函数动画化。我按照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()
答案 0 :(得分: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 Notebook时,通常会出现问题。
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.interactive(True)
plt.ion()
matplotlib.is_interactive()
答案 1 :(得分: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()