Search code examples
python-2.7matplotlibjupyter-notebookosx-elcapitan

Cannot close plot generated with matplotlib in ipython notebook


I am trying to make a plot using matplotlib in ipython notebook.

import matplotlib.pyplot as plt
plt.plot(range(10))
plt.show()

I get the desired plot, but when I try to close it, it hangs. I then have to force quit it, and restart the kernel.

If I run the same code from terminal, I can safely close the plot. The error is when using ipython notebook.

I am on OS X El Capitan (10.11.2), python 2.7. The issue began after updating to El Capitan.

Thanks in advance.


Solution

  • When your work in a notebook, it is better to display the plots inline. Turn on the inline mode:

    In: [1] %matplotlib inline
    

    Now, plot without the plt.show():

    In: [2]import matplotlib.pyplot as plt
    In: [3]plt.plot(range(10))
    

    The plot should appear right in the notebook.

    For interactive plots in the notebook use mpld3. Just add these lines to your notebook:

    import mpld3
    mpld3.enable_notebook()