97

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?

Kyle Kelley
  • 13,804
  • 8
  • 49
  • 78
8one6
  • 13,078
  • 12
  • 62
  • 84

7 Answers7

87

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.

javabrett
  • 7,020
  • 4
  • 51
  • 73
Kyle Kelley
  • 13,804
  • 8
  • 49
  • 78
  • 2
    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 Jan 17 '14 at 14:48
  • 3
    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. – 8one6 Jan 17 '14 at 14:50
  • 3
    This (as well as SillyBear's answer) stopped working with IPython 3. https://github.com/ipython/docker-notebook/pull/7#issuecomment-54729770 suggests to use "c.IPKernel.matplotlib"... which doesn't work neither. – Pietro Battiston Mar 29 '15 at 10:39
  • 3
    [This answer](http://stackoverflow.com/a/28970252/514210) 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. – DGrady Jun 04 '15 at 00:07
  • 3
    This option seems to have been renamed to `c.InteractiveShellApp.matplotlib = "inline"` – tiago Aug 26 '15 at 19:47
  • Gosh this must be coming up high on Google. Thanks for commenting @tiago. Seems I better put Jupyter centric config here too... – Kyle Kelley Aug 27 '15 at 02:52
  • 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` – Chris Warth Dec 02 '15 at 04:09
  • 1
    @ChrisWarth: [None of these settings work for me.](http://stackoverflow.com/q/36360015/656912) 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. – orome Apr 06 '16 at 15:59
  • 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. – timgeb Dec 30 '18 at 21:37
6

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.

Kyle Kelley
  • 13,804
  • 8
  • 49
  • 78
SillyBear
  • 125
  • 4
  • 1
    Please change your post to `--matplotlib inline` and remove the --pylab stuff. See this post of an ipython devel why: http://carreau.github.io/posts/10-No-PyLab-Thanks.ipynb.html – Jakob Jan 22 '14 at 15:22
  • 1
    One note about `matplotlib=inline`: It will slow down every kernel you launch, regardless of whether you want to use matplotlib. – Kyle Kelley Oct 06 '14 at 01:07
  • 7
    This no longer works (at least as of IPython 4). The command line options `--matplotlib` or `--pylab` are ignored. – tiago Aug 26 '15 at 19:45
  • 1
    The help for Jupyter command-line help says these options are disabled and should use `%pylab` or `%matplotlib` instead. – Cas Apr 07 '17 at 08:59
6

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

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
4

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

get_ipython().magic('matplotlib inline')
flow2k
  • 3,999
  • 40
  • 55
  • 1
    As of iPython 8.3, the correct format has become `get_ipython().run_line_magic('matplotlib', 'inline')`. – Alper Aug 16 '23 at 23:42
  • Thanks @Alper - would you have the link to the documentation by any chance? – flow2k Aug 18 '23 at 18:21
  • 1
    No problem. See https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html#IPython.core.interactiveshell.InteractiveShell.run_line_magic and https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html#IPython.core.interactiveshell.InteractiveShell.magic – Alper Aug 18 '23 at 18:31
3

In your ipython_config.py file, search for the following lines

# c.InteractiveShellApp.matplotlib = None

and

# c.InteractiveShellApp.pylab = None

and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
3

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()
memebrain
  • 403
  • 3
  • 9
2

Further to @Kyle Kelley and @DGrady, here is the entry which can be found in the

$HOME/.ipython/profile_default/ipython_kernel_config.py (or whichever profile you have created)

Change

# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.matplotlib = none

to

# Configure matplotlib for interactive use with the default matplotlib backend.
c.IPKernelApp.matplotlib = 'inline'

This will then work in both ipython qtconsole and notebook sessions.

Chris Hanning
  • 123
  • 1
  • 7