Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive matplotlib plots in jupyter notebook

The following snippet works as expected in ipython console:

> anaconda3/bin/ipython3
In [1]: import matplotlib.pyplot as plt
        import pandas as pd
        import numpy as np
In [2]: plt.ion()
In [3]: pd.Series(np.sin(np.arange(0, 10, 0.1))).plot() # plot window appears
In [4]: pd.Series(np.cos(np.arange(0, 10, 0.1))).plot() # second line is drawn in the same window

At no point is the terminal blocked. How to get the same behavior in Jupyter notebook? That is, an external interactive plot window that can be drawn onto incrementally from the notebook.

The same snippet displays no plots from the notebook. Executing plt.show() will display external window, but will block execution until window is closed.

Thanks in advance.

like image 728
qsd Avatar asked Sep 10 '16 16:09

qsd


People also ask

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.

How do I create an interactive 3D plot in matplotlib?

To generate an interactive 3D plot first import the necessary packages and create a random dataset. Now using Axes3D(figure) function from the mplot3d library we can generate a required plot directly. Pass the data to the 3D plot and configure the title and labels.

Can you use matplotlib in Jupyter notebook?

Matplotlib is a Python library that is used often with Jupyter Notebook.


2 Answers

Turns out %matplotlib magic is needed in the notebook even if no backend switch is required, after which notebook does behave the same as console. E.g., execute this as the first cell in a notebook:

%matplotlib
import matplotlib.pyplot as plt
plt.ion()
like image 105
qsd Avatar answered Oct 17 '22 18:10

qsd


Magic command %matplotlib makes jupyter notebook use Qt5Agg interactive back end.

like image 1
Never Too Old To Learn Avatar answered Oct 17 '22 18:10

Never Too Old To Learn