8

In IPython Notebook, I defined a function that contains a call to the magic function %matplotlib, like this:

def foo(x): %matplotlib inline # ... some useful stuff happens in between here imshow(np.asarray(img)) 

I'd like to put that function into a Python module so that I can just import and call it.

However, to do this, I'd need to remove the %matplotlib inline from my code and replace it with its pure-Python equivalent.

What is the pure-Python equivalent?

4
  • 1
    pyplot.show perhaps? not sure what you are really asking here Commented Feb 25, 2015 at 16:59
  • you can start your ipython notebook as ' ipython notebook --pylab inline' Commented Feb 25, 2015 at 17:59
  • never use --pylab flag, it is deprecated and does not work anymore. Commented Feb 25, 2015 at 19:17
  • This question is similar to: How to run IPython magic from a script. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Apr 6 at 2:21

2 Answers 2

10

%matplotlib inline directly hook into IPython instance. You can get the equivalent by using %hist -t that show you the processed input as pure python, which show that %matplotlib inline is equivalent to get_ipython().magic('matplotlib inline') in which get_ipython() return the current ipython shell object. It is pure python but will work only in an IPython kernel.

For more in depth explanation, %matplolib xxx just set matplotlib backend to xxx, the case od inline is a bit different and requires first a backend which is shipped with IPython and not matplotlib. Even if this backend was in matplotlib itself, it needs hooks in IPython itself to trigger the display and GC of matplotlib figures after each cell execution.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi , I tried this approach , but it returned AttributeError: 'NoneType' object has no attribute 'magic' . Any help ?
replying to the message above: It is pure python but will work only in an IPython kernel.. ■ Also .magic() is deprecated, use .run_line_magic or .run_cell_magic instead. ■ Without using IPython kernel you can start an embedded IPython kernel → stackoverflow.com/a/29621764
-2

I tried to comment out this line

get_ipython().run_line_magic('matplotlib', 'inline') 

and it worked for me.

2 Comments

How does it answer the question?
Does not work with Python 3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.