Automatically run %matplotlib inline in IPython Notebook

118,394

Solution 1

The configuration way

IPython has profiles for configuration, located at ~/.ipython/profile_*. The default profile is called profile_default. Within this folder there are two primary configuration files:

  • ipython_config.py
  • ipython_kernel_config.py

Add the inline option for matplotlib to ipython_kernel_config.py:

c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"

matplotlib vs. pylab

Usage of %pylab to get inline plotting is discouraged.

It introduces all sorts of gunk into your namespace that you just don't need.

%matplotlib on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.

import matplotlib.pyplot as plt
import numpy as np

The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.

Solution 2

I think what you want might be to run the following from the command line:

ipython notebook --matplotlib=inline

If you don't like typing it at the cmd line every time then you could create an alias to do it for you.

Solution 3

The setting was disabled in Jupyter 5.X and higher by adding below code

pylab = Unicode('disabled', config=True,
    help=_("""
    DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
    """)
)

@observe('pylab')
def _update_pylab(self, change):
    """when --pylab is specified, display a warning and exit"""
    if change['new'] != 'warn':
        backend = ' %s' % change['new']
    else:
        backend = ''
    self.log.error(_("Support for specifying --pylab on the command line has been removed."))
    self.log.error(
        _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
    )
    self.exit(1)

And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3

This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
 ],
 "display_name": "Python 3",
 "language": "python"
}

So you can see what command is executed to launch the kernel. So if you run the below command

$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.

Subcommands
-----------

Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.

install
    Install the IPython kernel

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Pre-load matplotlib and numpy for interactive use, selecting a particular
    matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Configure matplotlib for interactive use with the default matplotlib
    backend.
...    
To see all available configurables, use `--help-all`

So now if we update our kernel.json file to

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}

And if I run jupyter notebook the graphs are automatically inline

Auto Inline

Note the below approach also still works, where you create a file on below path

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'

But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

So choose which approach you would like to use based on your requirement

Solution 4

Create any .py file in ~/.ipython/profile_default/startup/ containing

get_ipython().magic('matplotlib inline')

Solution 5

In (the current) IPython 3.2.0 (Python 2 or 3)

Open the configuration file within the hidden folder .ipython

~/.ipython/profile_default/ipython_kernel_config.py

add the following line

c.IPKernelApp.matplotlib = 'inline'

add it straight after

c = get_config()
Share:
118,394
8one6
Author by

8one6

Updated on September 23, 2020

Comments

  • 8one6
    8one6 over 3 years

    Every time I launch IPython Notebook, the first command I run is

    %matplotlib inline
    

    Is there some way to change my config file so that when I launch IPython, it is automatically in this mode?

  • 8one6
    8one6 over 10 years
    Thanks. I had actually seen this config option in the matplotlib docs, but wasn't sure whether it just set the matplotlib backend that would take effect once you manually called %matplotlib or whether it both set the default backend and automatically set it up for use immediately in the iPython environment.
  • 8one6
    8one6 over 10 years
    To add to @Kyle Kelley's edit regarding matplotlib vs pylab, iPython makes it very easy to automatically execute arbitrary python code every time you launch using Profiles. I believe it is quite common to have a profile where you automatically do common imports like import numpy as np; import pandas as pd; import matplotlib.pyplot as plt, etc. NB: pylab is not the same thing as pyplot. It must have taken me a month to realize that.
  • Jakob
    Jakob over 10 years
    Please change your post to --matplotlib inline and remove the --pylab stuff. See this post of an ipython devel why: carreau.github.io/posts/10-No-PyLab-Thanks.ipynb.html
  • Kyle Kelley
    Kyle Kelley over 9 years
    One note about matplotlib=inline: It will slow down every kernel you launch, regardless of whether you want to use matplotlib.
  • Pietro Battiston
    Pietro Battiston about 9 years
    This (as well as SillyBear's answer) stopped working with IPython 3. github.com/ipython/docker-notebook/pull/7#issuecomment-54729‌​770 suggests to use "c.IPKernel.matplotlib"... which doesn't work neither.
  • DGrady
    DGrady almost 9 years
    This answer worked for me. In IPython 3 there's apparently a new configuration file, ipython_kernel_config.py, that contains this option. Make a new profile (ipython profile create test) to get a default.
  • tiago
    tiago over 8 years
    This no longer works (at least as of IPython 4). The command line options --matplotlib or --pylab are ignored.
  • tiago
    tiago over 8 years
    This option seems to have been renamed to c.InteractiveShellApp.matplotlib = "inline"
  • Kyle Kelley
    Kyle Kelley over 8 years
    Gosh this must be coming up high on Google. Thanks for commenting @tiago. Seems I better put Jupyter centric config here too...
  • Chris Warth
    Chris Warth over 8 years
    Can anyone supply the configuration filename and configuration line to set matplot inline by default in jupyter as of December 2015? I have been looking for hours and cannot get this to work. Is the name of the file ~/.jupyter/jupyter-notebook-config.py? Is the name of the option c.NotebookApp.matplotlib
  • orome
    orome about 8 years
    @ChrisWarth: None of these settings work for me. I'm not sure what the issue is but I expect either the options have changed or the location of the file has changed. I'm trying c.InteractiveShellApp.matplotlib = "inline" in ~/.jupyter/jupyter_notebook_config.py. My goal is to get this working in Jupyter notebooks (only) and leave shell IPython alone.
  • Cas
    Cas about 7 years
    The help for Jupyter command-line help says these options are disabled and should use %pylab or %matplotlib instead.
  • timgeb
    timgeb over 5 years
    Is there a way to just do %matplotlib on startup in a similar manner? I am currently doing get_ipython().magic('matplotlib') in the startup.py file, which seems like the wrong way of doing this.