How to change multiple interactive plots with a single input in Python

亡梦爱人 提交于 2019-12-22 09:35:50

问题


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)

来源:https://stackoverflow.com/questions/43963402/how-to-change-multiple-interactive-plots-with-a-single-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!