Exécuter automatiquement %matplotlib inline dans le bloc-notes IPython

chaque fois que je lance IPython Notebook, la première commande que j'exécute est

%matplotlib inline

y a-t-il un moyen de changer mon fichier de configuration pour que lorsque je lance IPython, il soit automatiquement dans ce mode?

70
demandé sur Kyle Kelley 2014-01-17 06:22:41

6 réponses

La configuration de la voie

IPython a des profils de configuration, situés à ~/.ipython/profile_* . Le profil par défaut est appelé profile_default . Dans ce dossier il y a deux fichiers de configuration:

  • ipython_config.py
  • ipython_kernel_config

ajouter l'option inline pour matplotlib à ipython_kernel_config.py :

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

matplotlib vs. pylab

L'utilisation de %pylab pour obtenir le tracé en ligne est découragé .

il introduit toutes sortes de gunk dans votre espace de nom dont vous n'avez pas besoin.

%matplotlib d'un autre côté permet le traçage en ligne sans injecter votre espace de nom. Vous aurez besoin de faire des appels explicites pour obtenir matplotlib et numpy importés.

import matplotlib.pyplot as plt
import numpy as np

Le petit prix de taper votre les importations explicitement devraient être complètement surmontées par le fait que vous avez maintenant code reproductible.

64
répondu Kyle Kelley 2016-04-25 10:49:53

je pense que ce que vous voulez pourrait être d'exécuter ce qui suit à partir de la ligne de commande:

ipython notebook --matplotlib=inline

si vous n'aimez pas le taper à la ligne cmd à chaque fois, vous pouvez créer un alias pour le faire à votre place.

6
répondu SillyBear 2014-09-12 03:12:06

dans votre fichier ipython_config.py , recherchez les lignes suivantes

# c.InteractiveShellApp.matplotlib = None

et

# c.InteractiveShellApp.pylab = None

et les décommentez. Ensuite, changez None pour le backend que vous utilisez (j'utilise 'qt4' ) et sauvegardez le fichier. Redémarrez IPython, et matplotlib et pylab doivent être chargés - vous pouvez utiliser la commande dir() pour vérifier quels modules sont dans l'espace de noms global.

3
répondu MattDMo 2014-01-17 14:56:38

(l'actuelle), IPython 3.2.0 (Python 2 ou 3)

Ouvrir le fichier de configuration dans le dossier caché .ipython

~/.ipython/profile_default/ipython_kernel_config.py

ajouter la ligne suivante

c.IPKernelApp.matplotlib = 'inline'

ajouter tout de suite après

c = get_config()
3
répondu memebrain 2015-07-12 14:12:45

le réglage a été désactivé dans Jupyter 5.X et plus en ajoutant ci-dessous le 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)

et dans les versions précédentes il a été principalement un avertissement. Mais ce n'est pas un gros problème car Jupyter utilise les concepts de kernels et vous pouvez trouver le noyau pour votre projet en exécutant la commande

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

cela me donne le chemin vers le dossier du noyau. Maintenant, si j'ouvre le fichier /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json , je vois quelque chose comme ci-dessous

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

pour que vous puissiez voir quelle commande est exécutée pour lancer le noyau. Donc, si vous exécutez la commande ci-dessous

$ 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`

donc maintenant si nous mettons à jour notre kernel.json fichier en

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

et si j'exécute jupyter notebook les graphiques sont automatiquement inline

Auto Inline

notez que l'approche ci-dessous fonctionne toujours, où vous créer un fichier sur le chemin d'accès ci-dessous

~/.ipython/profile_default/ipython_kernel_config.py

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

mais l'inconvénient de cette approche est qu'il s'agit d'un impact global sur chaque environnement utilisant python. Vous pouvez considérer cela comme un avantage aussi, si vous voulez avoir un comportement commun à travers des environnements avec un seul changement.

choisissez donc l'approche que vous souhaitez utiliser basé sur votre demande

3
répondu Tarun Lalwani 2018-05-11 16:25:19

suite à @Kyle Kelley et @dgrady, voici l'entrée qui se trouve dans le

$HOME/.ipython/profile_default/ipython_kernel_config.py (ou le profil que vous avez créé)

Changement

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

à

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

cela fonctionnera ensuite à la fois dans les sessions IPython qtconsole et notebook.

2
répondu Chris Hanning 2015-07-17 10:09:41