Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive plot in Jupyter notebook

I am trying to get 'realtime' ploting in Jupyter notebook. The example can be found here. Here is the code:

%matplotlib notebook

import numpy as np
import matplotlib.pyplot as pl

from random import randint
from time import sleep

from ipywidgets import FloatProgress
from IPython import display

siz = 10
dat = np.zeros((siz, siz))

fig = pl.figure()
axe = fig.add_subplot(111)
img = axe.imshow(dat)

num = 1000

prgBar = FloatProgress(min=0, max=num-1)
display.display(prgBar)

for i in range(num):
    prgBar.value = i
    pos = (randint(0, siz-1), randint(0, siz-1))
    dat[pos] += 1
    img.set_data(dat)
    img.autoscale()
    #sleep(0.01)

What I am aiming for is to see how the plot is changing with each itteration. I also tried set the interactive mod on by pl.ion(), changing backent to inline, calling pl.draw(), but non of it was working. BTW, the progressbar is working just fine...

Thanks Radek

like image 545
rad Avatar asked Mar 17 '16 17:03

rad


People also ask

Can you make interactive plots in Python?

Overall, if you are getting started with interactive plots using Python, Plotly can be a good choice to create simple plots with limited interactive components. But if you are looking to add a number of interactive components to your plots, then Altair is something you should really try your hands on.

Does matplotlib have interactive plots?

But did you know that it is also possible to create interactive plots with matplotlib directly, provided you are using an interactive backend? This article will look at two such backends and how they render interactivity within the notebooks, using only matplotlib.


1 Answers

The following code should do the trick:

import numpy as np
import matplotlib.pyplot as plt

from random import randint
from time import sleep

from ipywidgets import FloatProgress
from IPython.display import display, clear_output

siz = 10
dat = np.zeros((siz, siz))

fig = plt.figure()
axe = fig.add_subplot(111)
img = axe.imshow(dat)

num = 1000

prgBar = FloatProgress(min=0, max=num-1)
display(prgBar)

for i in range(num):
    clear_output(wait = True)
    prgBar.value = i
    pos = (randint(0, siz-1), randint(0, siz-1))
    dat[pos] += 1
    img.set_data(dat)
    img.autoscale()
    display(fig)

I changed the for loop creating the image on each step and also imported clear_output to clean the cell output on each step.

like image 60
kikocorreoso Avatar answered Nov 14 '22 23:11

kikocorreoso