16

Using Jupyter Notebook, I can create an animated plot (based on this sample code):

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

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def init():
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):
    line.set_ydata(np.sin(x + i / 100))  # update the data.
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=2, blit=True, save_count=50)

plt.show()

Is it possible to do so in Visual Studio Code's notebook editor? I think it involves the magic %matplotlib notebook mode which VS Code does not seem to support, but I don't know if there is an alternative.

rgov
  • 3,516
  • 1
  • 31
  • 51
  • [This blog post](http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/) talks about how to render an animation to an HTML5 plot that gets embedded, but this is not my goal: my plot will be updated based on a live data feed. – rgov Oct 30 '20 at 18:15

1 Answers1

25

Looks as though vscode supports ipywidgets (https://github.com/microsoft/vscode-python/issues/3429). So you can use the ipympl backend to matplotlib.

To use it you can use the %matplotlib ipympl magic.


%matplotlib notebook does some javascript injection that is very specific to jupyter notebook, so it will not work in vscode or even jupyter lab.

Ianhi
  • 2,864
  • 1
  • 25
  • 24