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?
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.
%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.
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.
%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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With