Skip to content
Advertisement

How to plot the sum of two animated sine waves in python?

Code:-

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()

This is the code I have tried to attain the result. But it u is static, that is it prints the final plot, and it only prints in a temporary window and closes after execution of the code.

But I need an answer which have three waves in the same output, where the first sine wave and second sine wave is added to obtain the final sine wave.

I want an answer which will be animated using numpy, matplotlib library of Python language.

I looked through subplot examples but I couldn’t merge the subplot module of matplotlib library with animation module of the matplotlib library.

Also, how can we save all the plots of the sine waves as a gif in local directory?

What library is required to export all three waves in a single gif file like the image? Anyone have a solution for this? Expected animated gif file

Advertisement

Answer

Check out this solution

  • To plot the sum of two sinusoidal in Python, I have used Matplotlib and NumPy to generate animated sine waves and exported the output as a gif file.
  • It is a customizable code where the equations and variables for X-axis and Y-axis can be changed in the animate() function.

Python code

    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')

Output (gif file)

Plotting Animated sum of two sinusoids in Python

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement