ussrback
ussrback

Reputation: 611

Plotting sum of two sinusoids in Python

I would like to plot sum of two sinusoidal in Python, like on attached screenshot. Could you please recommend how can i do it in matplotlib? enter image description here

Upvotes: 3

Views: 14435

Answers (5)

rpb
rpb

Reputation: 3299

This also can be achieve with seaborn

import pandas a pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
x = np.linspace(0, 6.5*np.pi, 200)
y1 = np.sin(x)
y2 = np.sin(2*x)
df=pd.DataFrame(dict(x=x,y1=y1,y2=y2))
df['diff']=df['y1']-df['y2']
df = pd.melt(df, id_vars='x', value_vars=['y1', 'y2','diff'],var_name='condition', value_name='y')

g = sns.FacetGrid(df, row="condition",
                  height=1.7, aspect=4,)
g.map_dataframe(sns.lineplot, "x",'y', alpha=1)

g.fig.subplots_adjust(hspace=-.1)
plt.show()

Output

enter image description here

Upvotes: 0

Aswin Barath
Aswin Barath

Reputation: 1097

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

Uniqueness

  • This Python code is unique because it plots animated sine waves using basic python libraries NumPy and Matplotlib along with the pillow library for image processing that is exporting the animated gif.

Upvotes: 2

Sheldore
Sheldore

Reputation: 39052

You already got two solutions. This one gives you something very similar to what you want. I could have made it look exactly like your output but I leave the remaining part of it as your exercise. Feel free to ask me if you have any doubts. This solution is based on https://matplotlib.org/examples/pylab_examples/finance_work2.html

import numpy as np
import matplotlib.pyplot as plt
left, width = 0.1, 0.8
rect1 = [left, 0.65, width, 0.25]  # left, bottom, width, height
rect2 = [left, 0.4, width, 0.25]
rect3 = [left, 0.1, width, 0.3]

fig = plt.figure(figsize=(10, 6))

ax1 = fig.add_axes(rect1) 
ax2 = fig.add_axes(rect2, sharex=ax1)
ax3 = fig.add_axes(rect3, sharex=ax1)

x = np.linspace(0, 6.5*np.pi, 200)
y1 = np.sin(x)
y2 = np.sin(2*x)

ax1.plot(x, y1, color='b', lw=2)
ax2.plot(x, y2, color='g', lw=2)
ax3.plot(x, y1+y2, color='r', lw=2)

ax3.get_xaxis().set_ticks([])

for ax in [ax1, ax2, ax3]:
    ax.hlines(0, 0, 6.5*np.pi, color='black')
    for key in ['right', 'top', 'bottom']:
        ax.spines[key].set_visible(False)

plt.xlim(0, 6.6*np.pi)
ax3.text(2, 0.9, 'Sum signal', fontsize=14)

Output

enter image description here

Upvotes: 4

Joe
Joe

Reputation: 12417

You can use this:

%matplotlib inline
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
from numpy import arange, sin, pi

t = arange(0.0, 2.0, 0.01)

fig = figure(1)

ax1 = fig.add_subplot(311)
ax1.plot(t, sin(2*pi*t))
ax2 = fig.add_subplot(312)
ax2.plot(t, sin(4*pi*t))
ax3 = fig.add_subplot(313)
ax3.plot(t, sin(4*pi*t)+sin(2*pi*t))
plt.show()

enter image description here

Upvotes: 3

mikinoqwert
mikinoqwert

Reputation: 415

Or something 'simpler':

import matplotlib.pyplot as plt
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)

x2 /= 2

sin3 = sin1+sin2

plt.plot(x,sin3)
plt.show()

enter image description here

Upvotes: 0

Related Questions