1

I'm trying to graph features of a data-set one by one by, via iteration. So I want the graph to continuously update as I proceed through the loop.

I refered to this thread,real-time plotting in while loop with matplotlib but the answers are all over the place, and despite incorporating some of their suggestions as shown below, I still can't seem to get the code working. I'm using Jupyter Notebook.

import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
colors = ["darkblue", "darkgreen"]

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, sharex = True)


for i in range(X.shape[-1]-1):
    idx = np.where(y == 1)[0]
    ax1.scatter(X[idx, i], X[idx, i+1], color=colors[0], label=1)


    idx = np.where(y == 0)[0]
    ax2.scatter(X[idx, i], X[idx, i+1], color=colors[1], label=0)

    plt.draw()
    plt.pause(0.0001)

Any suggestions?

Thank you.

vestland
  • 55,229
  • 37
  • 187
  • 305
Moondra
  • 4,399
  • 9
  • 46
  • 104

2 Answers2

2

For an animation you need an interactive backend. %matplotlib inline is no interactive backend (it essentially shows a printed version of the figure).

You may decide not to run you code in jupyter but as a script. In this case you would need to put plt.ion() to put interactive mode on.

Another option would be to use a FuncAnimation, as e.g in this example. To run such a FuncAnimation in Jupyter you will still need some interactive backend, either %matplotlib tk or %matplotlib notebook.

From matplotlib 2.1 on, we can also create an animation using JavaScript.

from IPython.display import HTML
HTML(ani.to_jshtml())

Some complete example:

import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

from IPython.display import HTML
HTML(ani.to_jshtml())
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
2

This is an example for real-time plotting in a Jupyter Notebook

%matplotlib inline
%load_ext autoreload  #Reload all modules every time before executing the Python code typed.
%autoreload 2 
%matplotlib notebook

import matplotlib.pyplot as plt
import numpy as np
import time

colors = ["darkblue", "darkgreen"]

# initialise the graph and settings

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = fig.add_subplot(211)
plt.ion() # interactive mode
fig.show()
fig.canvas.draw() # matplotlib canvas drawing

# plotting loop

for i in range(X.shape[-1]-1):
  ax1.clear()
  ax2.clear()

  idx = np.where(y == 1)[0]
  ax1.scatter(X[idx, i], X[idx, i+1], color=colors[0], label=1)

  idx = np.where(y == 0)[0]
  ax2.scatter(X[idx, i], X[idx, i+1], color=colors[1], label=0)

  fig.canvas.draw() # draw
  time.sleep(0.5)   # sleep
mforpe
  • 1,549
  • 1
  • 12
  • 22