3

I am just looking for some kind of working example which will allow me to have a slider and a sine wave plot whereby I can vary the frequency in a Jupyter Notebook. All the online demos that I have Googled don't work for me. The issue seems to be that the old matplotlib graph is not erased before the new one is created.

Here is my minimal example

import ipywidgets as widgets
from IPython.display import display, clear_output
import matplotlib.pyplot as plt
import numpy as np

def f(a):
    clear_output(wait=True)
    fig, ax = plt.subplots()
    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(a*x)
    ax.grid()
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.plot(x,y)
    ax.set_title("y = sin(x)")

%matplotlib inline
from time import sleep
for i in range(1,10):
    clear_output(wait=True)
    f(i)
    sleep(1)

I have also tried

out = widgets.Output(layout={'border': '1px solid black'})
with out:
    widgets.interact(f, a=1)
    out.clear_output()
    display(out)

However nothing I try will erase the previous matplotlib graph. They just all pile up on top of each other. I admit I am floundering as I don't really understand the API that well and the example in the documentation don't work for me.

I don't expect people to fix my code as it is probably rubbish. I am just looking for a working example which will allow me to interactively control the frequency and redraw the sine wave on a Jupyter notebook.

Kiwiheretic
  • 308
  • 2
  • 12

1 Answers1

3

Here is a minimal example that works for me:

from ipywidgets import interact
import ipywidgets as widgets

import matplotlib.pyplot as plt
import numpy as np

def plot(freq):
    x = np.linspace(0, 2*np.pi)
    y = np.sin(x * freq)
    plt.plot(x, y)

interact(plot, freq = widgets.FloatSlider(value=2, min=0.1, max=5, step=0.1))

default plot:

default

Screenshot of notebook after moving the slider to the right:

screenshot

mozway
  • 194,879
  • 13
  • 39
  • 75
  • When I do that I don't even get a slider and I am using the official jupyter/scipy-notebook docker image. https://ibb.co/gwHZWpR – Kiwiheretic Aug 09 '21 at 01:20
  • Have you properly installed and activated ipywidgets? In your shell, run `pip install ipywidgets` and `jupyter nbextension enable --py widgetsnbextension`. – mozway Aug 09 '21 at 02:23
  • The widgets will display using the RangeSliders but just not via interact – Kiwiheretic Aug 10 '21 at 01:15