我正在尝试用python制作一些正弦波动画,然后可以将其导出为.gif格式。我正在尝试使用matplotlib的PillowWriter函数在Visual Studio中执行此操作。我不断收到此“列表索引超出范围”错误,似乎无法解决。感谢您对我做错的任何想法。作为记录,我对编程非常不了解,并且刚刚决定自学使用Python在隔离期间进行数据可视化,因此,不幸的是,我对Python,VS等不是一个新手。在此先感谢您的任何建议。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
plt.style.use('seaborn-pastel')
fig = plt.figure()
ax = plt.axes(xlim=(-15, 15), ylim=(-6, 6))
line1, = ax.plot([], [], lw=3)
line2, = ax.plot([], [], lw=3)
line3, = ax.plot([], [], lw=6)
line4, = ax.plot([], [], lw=3)
def init():
line1.set_data([], [])
line2.set_data([], [])
line3.set_data([], [])
line4.set_data([], [])
return line1, line2, line3, line4,
def animate(i):
x = np.linspace(-15, 15, 4000)
y = np.sin(0.21 * np.pi * (x - 0.23 * i))
y2 = np.sin(0.311 * np.pi * (x - 0.19 * i)+2.1)
y3 = np.sin(0.307 * np.pi * (x - 0.29 * i)+4.2)
y4 = np.sin(0.3 * np.pi * (x - 0.4 * i))
##yz = np.sin(0.5(freq) * np.pi * (x - 0.4(speed) * i)(displacement))
y5 = y+y2
y6 = y3+y5+y5+y4
y8 = y+y2+y3
y7 = y8+y4
#line1.set_data(x, 5)
#line2.set_data(x, y6)
line3.set_data(x, y6)
#line4.set_data(x, y8)
return line1, line2, line3, line4,
anim = FuncAnimation(fig, animate, init_func=init,
frames=2000, interval=25, blit=True)
writer = PillowWriter(fps=20)
anim.save("sinewaves.gif", writer=writer)
plt.show()
这是试图保存的倒数第二行,这是错误所在。
我不确定您是如何编码的,因为我本人还是一个初学者。但是我有自己的方式:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10,10,100)
for n in range(7):
plt.xticks([])
plt.yticks([])
plt.ylim(-2,2)
plt.plot(x,np.sin(x))
plt.savefig(str(n)+'.png')
plt.close()
x += 1
from PIL import Image,ImageFilter
images = []
for n in range(7):
exec('a'+str(n)+'=Image.open("'+str(n)+'.png")')
images.append(eval('a'+str(n)))
images[0].save('sin.gif',
save_all=True,
append_images=images[1:],
duration=100,
loop=0)