How to change multiple interactive plots with a si

2019-05-16 18:58发布

问题:

I am trying to make several interactive plots with the ipywidgets library in Jupyter Notebook. I face however one problem: I try to make multiple plots change when one single input widget changes, for example a slider.

In the added MWE this is illustrated with a sine and cosine function that both depend 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 at the value 2, the amplitude of both the sine and cosine function must inmediately follow suit.

If you would run the code yourself then you will see that both sliders move together perfectly. But, not both plots 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)