Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get any kind of interactive plot with ipywidgets and matplotlib

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.

like image 736
Kiwiheretic Avatar asked Oct 27 '25 11:10

Kiwiheretic


1 Answers

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

like image 171
mozway Avatar answered Oct 29 '25 10:10

mozway