Struggling to get widgets working in python

133 views Asked by At

I don't know why but I am really struggling to get widgets working well in python. I try to look at examples about how to use them but I don't know how to extrapolate that to get it to work with my code. I am trying to get a figure to display widgets such that the type, frequency, phase, and other variables adjust the graph itself.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
from scipy import signal
from matplotlib.widgets import RadioButtons

A = 1
ang_f = 5
t = np.linspace(0, 4*np.pi, 1000)
phase = 0

s0 = A*np.sin(ang_f*t + phase)
s2 = A*signal.sawtooth(ang_f*t + phase)
s1 = A*signal.square(ang_f*t + phase)

fig, ax = plt.subplots()
l, = ax.plot(t, s1, lw=2, color='red')
plt.subplots_adjust(left=0.4)


def sinf(x, omega):
    return np.sin(omega*x)


def sliderCallback(val):
    #  """ 'val' is the current value selected by the slider
    #    Recalculate sine values with val as the frequency """
    axesHandle.set_ydata(sinf(x, val))
    plt.draw()  # Redraw the axes


def clickcallback(val):
    #   'val' is the current value selected by the slider
    #    Recalculate sine values with val as the frequency
    axesHandle.set_ydata(sinf(x, val))
    plt.draw()  # Redraw the axes


def closeCallback(event):
    plt.close('all')  # Close all open figure windows


fig = plt.figure(figsize=(7, 5))
ax = plt.axes([0.1, 0.2, 0.6, 0.7])

axesHandle, = plt.plot(x, sinf(x, 1), lw=2, color='red')

# Add axis to contain the slider
fax = plt.axes([0.1, 0.04, 0.35, 0.03])    # Frequency
tax = plt.axes([0.1, 0.12, 0.35, 0.03])    # Time
sax_3 = plt.axes([0.60, 0.1, 0.35, 0.03])  # Number of points
pax = plt.axes([0.60, 0.05, 0.35, 0.03])    # Phase
rax = plt.axes([0.85, 0.65, 0.12, 0.15])    # Type
bax = plt.axes([0.85, 0.85, 0.1, 0.1])    # Close

pointshandle = widgets.Slider(sax_3, 'Number of points', 1, 200,
                              valfmt='%0.0f')
pointshandle.on_changed(sliderCallback)

graphchoice = widgets.RadioButtons(rax, ('Sine', 'Squarewave', 'Sawtooth'))
graphchoice.on_clicked(clickcallback)

freqhandle = widgets.Slider(fax, 'Frequancy (Hz)', 0, 5, valinit=1)
freqhandle.on_changed(sliderCallback)

phasehandle = widgets.Slider(pax, 'Phase', 0, 0*np.pi, valinit=0)
phasehandle.on_changed(sliderCallback)

timehandle = widgets.Slider(tax, 'Time (s)', 1, 10, valinit=1)
timehandle.on_changed(sliderCallback)

buttonHandle = widgets.Button(bax, 'Close')
buttonHandle.on_clicked(closeCallback)


def hzfunc(label):
    hzdict = {'Sine': s0, 'Squarewave': s1, 'Sawtooth': s2}
    ydata = hzdict[label]
    l.set_ydata(ydata)
    plt.draw()


graphchoice.on_clicked(hzfunc)

I'm really lost so any tips to put me on the right path would be much appreciated, im just so confused atm.

0

There are 0 answers