Search code examples
pythonmatplotlibvisual-studio-codejupyter-notebookmatplotlib-animation

Missing Matplotlib Animated Figure in VSCode Jupyter Notebook


I am trying to create a simple matplotlib animation in a Jupyter notebook running inside vscode.

%matplotlib notebook

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
line, = ax.plot([])     # A tuple unpacking to unpack the only plot
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.1, 1.1)

def animate(frame_num):
    y = np.sin(x + 2*np.pi * frame_num/100)
    line.set_data((x, y))
    return line

anim = FuncAnimation(fig, animate, frames=100, interval=5)
plt.show()

However, no figure appears after running the cell, just the green tick symbol.

enter image description here

Using Jupyter extension, both release version v2022.11.1003412109 and pre-release version v2023.1.1003441034.

Is it possible to get the animated matplotlib figure to work inside Vscode Jupyter notebook?


Solution

  • %matplotlib notebook

    As the yellow wavy line says, '%matplotlib' widget works best inside of VS Code.

    We use %matplotlib widget instead of %matplotlib notebook,tk,etc.

    VS code should work with these two options (has been thoroughly tested):

    • %matplotlib inline - This is the default and will render images as PNGs
    • %matplotlib widget - This generates an ipywidget that renders plots in a control. Multiple plots and zooming are supported. For more information see the README

    %matplotlib notebook is unsupported.

    You can use this command with the web version of jupyter notebook.

    Read this document for more information.