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.

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

3 Comments

@Minato added example.
@garyp no, not as far as I remember, hence the question. I think I found it accidentally by using the %magic for unrelated things.
Where is the example added? I am still having the plot in a new figure outside the notebook
1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.