Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pure Python equivalent to the IPython magic function call %matplotlib inline?

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?

like image 844
coffee-grinder Avatar asked Feb 25 '15 16:02

coffee-grinder


People also ask

What is %Matplotlib inline in Python?

Magic commands perform special functions in the IPython shell. Matplotlib Inline command is a magic command that makes the plots generated by matplotlib show into the IPython shell that we are running and not in a separate output window.

Why %Matplotlib inline is used in Python?

%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

What is IPython magic function?

Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself.


1 Answers

%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.

like image 54
Matt Avatar answered Oct 08 '22 19:10

Matt