代码:-
import numpy as np
x = np.arange(0,10,0.01)
x2 = np.arange(0,20,0.02)
sin1 = np.sin(x)
sin2 = np.sin(x2)
sin3 = sin1+sin2
plt.plot(x,sin3)
plt.show()
这就是我试图达到的结果。但它是静态的,即它打印最后的绘图,它只在一个临时窗口中打印,并在代码执行后关闭。
但是我需要一个答案,在相同的输出中有三个波,其中第一个正弦波和第二个正弦波相加,得到最后的正弦波。
我想要的答案将是动画使用numpy,matplotlib库的Python语言。
我查看了子图示例,但无法将matplotlib库的子图模块与matplotlib库的动画模块合并。
另外,我们如何将正弦波的所有图形保存为本地目录中的gif?
需要什么库才能像图像一样在一个gif文件中导出所有三个波形?有人有办法解决这个问题吗?预期动画gif文件
发布于 2020-11-27 18:51:57
看看这个解决方案
animate()
函数中更改。Python代码
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, sharey=True)
fig.suptitle('Sine waves')
ax1.set_xlim(0, 4)
ax1.set_ylim(-4, 4)
line1, = ax1.plot([], [], color='r', lw=3)
line2, = ax2.plot([], [], color='g', lw=3)
line3, = ax3.plot([], [], color='b', lw=6)
plt.legend([line1, line2, line3],['sin(x1)', 'sin(x2)', 'sin(x1)+sin(x2)'])
def init():
line1.set_data([], [])
line2.set_data([], [])
line3.set_data([], [])
return line1, line2, line3
def animate(i):
x1 = np.linspace(0, 4, 1000)
y1 = np.sin(2 * np.pi * (1.1*x1 - 0.05 * i))
line1.set_data(x1, y1)
x2 = np.linspace(0, 4, 1000)
y2 = np.sin(2 * np.pi * (1.21 * x2 - 0.04 * i))
line2.set_data(x2, y2)
x3 = np.linspace(0, 4, 1000)
y3 = np.sin(2 * np.pi * (1.1*x3 - 0.05 * i)) + np.sin(2 * np.pi * (1.21 * x3 - 0.04 * i))
line3.set_data(x3, y3)
return line1, line2, line3
anim1 = FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
anim1.save('sine_wave.gif', writer='imagemagick')
输出(gif文件)
https://stackoverflow.com/questions/65042428
复制相似问题