Python Matplotlib – What Does %matplotlib Inline Do in Jupyter & IPython?

matplotlibpython

I'm curious that how jupyter notebook enables the plot inline.
I searched %matplotlib inline in github and didn't find the source code (https://github.com/search?l=python&q=org%3Ajupyter+matplotlib+inline&ref=searchresults&type=Code&utf8=%E2%9C%93).

And it is not avaiable in the docs (http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-matplotlib).

Could anyone tell me where can I see the source code of %matplotlib inline?

Best Answer

You can find the source of the matplotlib magic in a jupyter notebook via

%matplotlib?? # view source

From this we find the code in python3.5/site-packages/IPython/core/magics/pylab.py

    args = magic_arguments.parse_argstring(self.matplotlib, line)
    if args.list:
        backends_list = list(backends.keys())
        print("Available matplotlib backends: %s" % backends_list)
    else:
        gui, backend = self.shell.enable_matplotlib(args.gui)
        self._show_matplotlib_backend(args.gui, backend)

The line that is doing the work is self.shell.enable_matplotlib. You can find this in the IPython github repository: https://github.com/ipython/ipython/blob/aa586fd81940e557a1df54ecd0478f9d67dfb6b4/IPython/core/magics/pylab.py#L100

This calls code from interactiveshell.py: https://github.com/ipython/ipython/blob/aa586fd81940e557a1df54ecd0478f9d67dfb6b4/IPython/core/interactiveshell.py#L2918-L2961