PLOTS sliderΒΆ

# -*-Python-*-
# Created by bgrierson at 14 Dec 2016  06:10

# Traveling wave

# Space dimension
xmin = 0.0
xmax = 1.0
nx = 101
x = linspace(xmin, xmax, nx)
dx = x[1] - x[0]

# Time dimension
tmin = 0.0
tmax = 2.0
nt = 1024
t = linspace(tmin, tmax, nt)
dt = t[1] - t[0]

# Wavelength (m)
lam = 0.25
k = 2.0 * np.pi / lam

# Frequency (Hz)
f = 5.0
omega = 2.0 * np.pi * f

# Phase shift of second signal
phi = np.pi / 4.0

# 2D (t,x) array
tt, xx = meshgrid(t, x)
y1 = np.cos(k * xx - omega * tt)
y2 = np.cos(k * xx - omega * tt + phi)

# At this point we have two 2D arrays in space and time
# We wish to display with a slider, that plots in space
# and slides forwards and backwards in time.

# Get the graphic handle, which we will use to create
# many line opbjects to fill the slider tool.
# This way, we're not re-making the plot, just sliding
# back and forth between existing plot objects.
fig, ax = plt.subplots()
ax.set_title('Traveling Wave')
ax.set_xlabel('x')
ax.set_ylabel('y1,y2')

# Change the width to allow for the slider below
plt.subplots_adjust(left=0.15, bottom=0.25)

# Set axes to maxima
plt.axis([np.amin(x), np.amax(x), np.amin(y1), np.amax(y1)])

# Make two line objects, one for each plot we will make (two signals)
lines = [plt.plot([], [])[0], plt.plot([], [])[0]]

# Set initial data for each signal we draw
lines[0].set_data(x, y1[:, 0])
lines[1].set_data(x, y2[:, 0])

# Set the colors of each signal
lines[0].set_color('b')
lines[1].set_color('g')

# Create an axes object for the sliderl
axstime = plt.axes([0.15, 0.1, 0.70, 0.03])

# Create the slider propoerties
stime = Slider(axstime, 'Time', np.amin(t), np.amax(t), valinit=np.amin(t), valfmt='%1.3f')

# Create the function to update the plot when the slider is changed.
def update(tval):
    idx = np.searchsorted(t, tval)
    lines[0].set_data(x, y1[:, idx])
    lines[1].set_data(x, y2[:, idx])
    fig.canvas.draw()


# Assign the update function to the slider object
stime.on_changed(update)

# Show the plot and begin interacting
plt.show()