#!/usr/bin/env python # coding: utf-8 # ## Basic Matplotlib interactive plot adjustable via widgets # # # I was delighted to see that the newer JupyterLab seemed to have much better support for ipywidgets lately and so when I saw [this question](https://stackoverflow.com/q/67804804/8508004) at StackOverflow, I thought it was a good time to test how the solution proposed was working. # In examining [the current answer](https://stackoverflow.com/a/67816794/8508004) to [this question](https://stackoverflow.com/q/67804804/8508004), I was finding the answer wasn't working in repositories where I had ipywidgets enabled, even when I tried in JupyterLab. # # However, the ipywidgets documentation includes [a matplotlib example](https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html?highlight=matplotlib#Flickering-and-jumping-output) (found by searching 'matplotlib' in the documentation). # # # ```python # %matplotlib inline # from ipywidgets import interactive # import matplotlib.pyplot as plt # import numpy as np # # def f(m, b): # plt.figure(2) # x = np.linspace(-10, 10, num=1000) # plt.plot(x, m * x + b) # plt.ylim(-5, 5) # plt.show() # # interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5)) # output = interactive_plot.children[-1] # output.layout.height = '350px' # interactive_plot # ``` # # I was able to take that and adapt @queezz's [solution](https://stackoverflow.com/a/67816794/8508004) to get it working. # # (Note when I did this, going to @queezz's repo [here](https://github.com/queezz/Complex_Numbers) and launching a binder session and opening the [MatplotliInteractTest.ipynb](https://github.com/queezz/Complex_Numbers/blob/3b15605d6edb63a833ca9357f6938b28c233314f/MatplotliInteractTest.ipynb) apparently meant to accompany, the answer, didn't allow the plot to work either. It said I suspect locking in the versions wasn't the best choice?) # In[1]: #%matplotlib inline # from the example in the documentation. but doesn't seem necessary in current JupyterLab 3.1.11 or the classic notebook available now https://github.com/fomightez/communication_voila from ipywidgets import interactive import matplotlib.pyplot as plt import numpy as np def my_sine(x, w, amp, phi): """ Return a sine for x with angular frequency w and amplitude amp. """ return amp*np.sin(w * (x-phi)) def f( w, amp, phi): plt.figure(2) x = np.linspace(0, 2 * np.pi, 300) plt.plot(x, my_sine(x, w, amp, phi), color='C0') #plt.ylim(-5, 5) plt.grid(True) #optional grid plt.show() interactive_plot = interactive(f, w=(0, 10, 1), amp=(0, 4, .1), phi=(0, 2*np.pi+0.01, 0.01)) #output = interactive_plot.children[-1] #output.layout.height = '450px' interactive_plot # In[ ]: