How to change multiple interactive plots with a single Python login

I am trying to make some interactive plots with the ipywidgets library in a Jupyter Notebook. I am facing one problem: I am trying to change multiple graphs when one input widget, like a slider, changes.

In the added MWE, this is illustrated by a sine and cosine function that depends on a single input widget that sets the amplitude of both the sine and the cosine function. Thus, if the value of the input slider is set to a value of 2, the amplitude of both the sine and cosine functions should immediately follow suit.

If you run the code yourself, you can see that both sliders move perfectly together. But not both graphs change at the same time accordingly.

Does anyone have a solution for this? Not necessarily with ipywidgets?

Thank you in advance,

Rick

# FIRST JUPYTER NOTEBOOK CELL
import matplotlib.pyplot as plt
from ipywidgets import *
from math import * 
import numpy as np
%matplotlib inline

default_value = 1  # Default value of amplutide 

a = IntSlider(min = 1, max = 10, value = default_value, description = 'Amplitude of sine function')
b = IntSlider(min = 1, max = 10, value = default_value, description = 'Amplitude of sine function')

mylink = jslink((a, 'value'), (b, 'value'))

def widget_sine_function(amp_s = a):
  x = np.linspace(0,20,100000)  # Creat x-values for sine function
  y = [amp_s*sin(i) for i in x]  # Create y-values for sine function with amplitude according to value of widget a
  plt.clf()
  plt.figure(figsize=(15,5))
  plt.subplot(1, 2, 1)
  plt.plot(x,y)

interact(widget_sine_function)

# SECOND JUPYTER NOTEBOOK CELL
def widget_cosine_function(amp_c = b):
  x = np.linspace(0,20,100000)  # Creat x-values for cosine function
  y = [amp_c*cos(i) for i in x]  # Create y-values for cosine function with amplitude according to value of widget b
  plt.clf()
  plt.figure(figsize=(15,5))
  plt.subplot(1, 2, 1)
  plt.plot(x,y)

interact(widget_cosine_function)

      

+3


source to share





All Articles