Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter: How to update plot on button click (ipywidgets)

I am using Jupyter and trying to make my plots interactive.

So I have a plot. I have a ipywidgets button.

On button click I need to update plot, like interact do with sliders.

But I can't.

It works only if matplotlib uses 'notebook' backend, but it looks terrible. At same time interact works with any kind of plots. Are there any way to reproduce this, not using interact?

#this works fine! But toolbar near the graph is terible
#%matplotlib notebook 

#this does not work
%matplotlib inline

from matplotlib.pyplot import *
button = ipywidgets.Button(description="Button")

def on_button_clicked(b):
    ax.plot([1,2],[2,1])

button.on_click(on_button_clicked)

display(button)

ax = gca()
ax.plot([1,2],[1,2])
show()
like image 427
Anton Ovsyannikov Avatar asked Dec 18 '17 23:12

Anton Ovsyannikov


People also ask

What does %Matplotlib do in Jupyter?

In the IPython notebook, you also have the option of embedding graphics directly in the notebook, with two possible options: %matplotlib notebook will lead to interactive plots embedded within the notebook. %matplotlib inline will lead to static images of your plot embedded in the notebook.

How do you increase the size of a plot in Jupyter notebook?

Next, to increase the size of the plot in the jupyter notebook use plt. rcParams[“figure. figsize”] method and set width and height of the plot.

What is the %Matplotlib inline?

You can use the magic function %matplotlib inline to enable the inline plotting, where the plots/graphs will be displayed just below the cell where your plotting commands are written. It provides interactivity with the backend in the frontends like the jupyter notebook.


1 Answers

As workaround we can repaint the whole plot to Output widget and then display it without flickering.

%matplotlib inline

from matplotlib.pyplot import *

button = ipywidgets.Button(description="Button")
out = ipywidgets.Output()

def on_button_clicked(b):
    with out:
        clear_output(True)
        plot([1,2],[2,1])
        show()

button.on_click(on_button_clicked)

display(button)

with out:
    plot([1,2],[1,2])
    show()

out
like image 83
Anton Ovsyannikov Avatar answered Oct 02 '22 20:10

Anton Ovsyannikov