import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots(facecolor='w',figsize=(10,5))
plt.subplots_adjust(left=0.05, bottom=0.25)
tmin,tmax = -.2,1.8
t = np.linspace(tmin,tmax, 2000)

a0 = 5000
a1 = a0
f0 = 40
f1 = 30
offset = 2.

amplitude = 1/(f1**2-f0**2)/(2*np.pi)**2
s0 = a0*amplitude*np.cos(2*np.pi*f0*t)
s1 = a1*amplitude*np.cos(2*np.pi*f1*t)

l0, = plt.plot(t,s0    + -1.5*offset, lw=2, color='red'  , alpha=0.5 )
l1, = plt.plot(t,s1    + -0.5*offset, lw=2, color='orange', alpha=0.65 )
l2, = plt.plot(t,s1+s0 +  1.0*offset, lw=2, color='blue' , alpha=0.75)

plt.yticks([])
plt.title('blue = orange - red')
plt.axis([tmin,tmax, -5, 5])
plt.axvline(0,color='k',alpha=0.25)
#plt.xlabel('t'); 
plt.ylabel('x(t)   ',rotation=0)

axcolor = 'white'
axfreq0 = plt.axes([0.25, 0.1 , 0.65, 0.03])#, bg=axcolor)
axfreq1 = plt.axes([0.25, 0.15, 0.65, 0.03])#, axisbg=axcolor)

sfreq0 = Slider(axfreq0, '  red frequency', 0.1, 150.0, valinit=f0, color='red'  )
sfreq1 = Slider(axfreq1, 'orange frequency', 0.1, 150.0, valinit=f1, color='orange')

def update(val):
    freq0 = sfreq0.val
    freq1 = sfreq1.val
    amplitude = 1/(freq1**2-freq0**2)/(2*np.pi)**2
    s0 = a0*amplitude*np.cos(2*np.pi*freq0*t)
    s1 = a1*amplitude*np.cos(2*np.pi*freq1*t)
    l0.set_ydata(s0    + -1.5*offset)
    l1.set_ydata(s1    + -0.5*offset)
    l2.set_ydata(s1-s0 +  1.0*offset)
    fig.canvas.draw_idle()


sfreq0.on_changed(update)
sfreq1.on_changed(update)

plt.show()
