Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 479
aph Avatar asked Dec 02 '25 08:12

aph


2 Answers

Use this instead:

from IPython import get_ipython
ipython = get_ipython()
if ipython:
    ipython.magic("matplotlib inline")
like image 161
pgy Avatar answered Dec 04 '25 00:12

pgy


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
like image 38
benjimin Avatar answered Dec 03 '25 23:12

benjimin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!