简体   繁体   中英

including plots in an IPython Notebook without %matplotlib magic function

Setup:

I have an IPython Notebook I'd like to include in the tutorials section of my docs. I've written a .ipynb —> .rst conversion script (using pandoc) that works as follows: the notebook is first converted to a .py file, which is executed as a script, and if the script execution raises no exceptions, an .rst export is triggered and a link to that tutorial is built in the appropriate spot of the docs. That way, the tutorials can be integrated into my docs only under the condition that the code does what the tutorial says it does. This method was developed as a result of the following question: Raise exception if script fails

Ok, so here is the problem. I'd like for some of the .ipynb tutorials to include in-line plots with matplotlib. The way I display plots in an IPython Notebook is using the magic function call:

%matplotlib inline 

However, if this command appears in a python executable script, python raises an exception. So none of my tutorials can currently include plots.

Question:

So my question is this: how can I include in-line plots in a Notebook in a way that will not raise an exception when the notebook is exported to a .py file and executed as a script? Or, short of that, any suggestions for another workaround?

Use this instead:

from IPython import get_ipython
ipython = get_ipython()
if ipython:
    ipython.magic("matplotlib inline")

Currently, there should be no real need to use %matplotlib inline magic in jupyter. Instead, this should display nicely:

import matplotlib.pyplot as plt
fig, ax = plt.subplot(111)
ax.plot([3,4,2,5])
fig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM