Statistic Dean
Statistic Dean

Reputation: 5270

How to make dependent sliders in matplotlib

Similar to Matplotlib dependent sliders, I want to make two sliders whose sum make 10. To do that, i want that when i move one slider, the other one moves to compensate. At the moment, the code is the following :

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

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 5
delta_f = 5.0
s = a0*np.sin(2*np.pi*f0*t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -10, 10])

axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 10.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

def update_sfreq(val):
    samp.val = 10-sfreq.val
    l.set_ydata(samp.val*np.sin(2*np.pi*sfreq.val*t))
    fig.canvas.draw_idle()

sfreq.on_changed(update_sfreq)

resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


def reset(event):
    sfreq.reset()
    samp.reset()
button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()
radio.on_clicked(colorfunc)

plt.show()

This is one of matplotlib examples that I modified to suit my needs. At the moment, I only implemented s_freq.on_changed(). I want that when I move the freq slider, the graph changes (This part is working), and at the same time, the amp slider moves too (This part is not).

Any thoughts on how to modify my function update_sfreq to correctly update samp?

Note : I do realize that if both my sliders update each other, I might end up in an infinite loop. I have already thought of this and of a solution. The part that is not working is really the part where moving one slider makes the other slider move.

Upvotes: 2

Views: 149

Answers (1)

Statistic Dean
Statistic Dean

Reputation: 5270

Well, after some digging in matplotlib source code, I managed to find an answer to my question. You need to change

samp.val = ... 

to

samp.set_val(...)

This will update the bar correctly.

Upvotes: 2

Related Questions