5

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.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
qsd
  • 151
  • 1
  • 1
  • 7

3 Answers3

10

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()
qsd
  • 151
  • 1
  • 1
  • 7
1

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

0

To imitate a blocking call to plt.show() with interactive backend you need to wait until your figure is active.

# provided interactive backend
# e.g. %matplotlib qt5
fig = plt.figure()

plt.show()

try:
    while fig.number in plt.get_fignums():
        plt.pause(0.1)
except:
    plt.close(fig.number)
    raise

The exception case closes the figure's window when a user presses Interrupt the kernel (aka Stop) button in Jupyter Notebook.

Pak Uula
  • 2,750
  • 1
  • 8
  • 13