Cómo hacer IPython notebook matplotlib plot inline


Estoy tratando de usar IPython notebook en macOS X con Python 2.7.2 e IPython 1.1.0.

No puedo hacer que los gráficos matplotlib se muestren en línea.

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

También he probado %pylab inline y los argumentos de la línea de comandos de ipython --pylab=inline pero esto no hace ninguna diferencia.

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

En lugar de gráficos en línea, obtengo esto:

<matplotlib.figure.Figure at 0x110b9c450>

Y matplotlib.get_backend() muestra que tengo el 'module://IPython.kernel.zmq.pylab.backend_inline' backend.

Author: Michael Currie, 2013-10-16

10 answers

Usé %matplotlib inline en la primera celda del cuaderno y funciona. Creo que deberías probar:

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

También puede iniciar siempre todos sus núcleos IPython en modo inline de forma predeterminada estableciendo las siguientes opciones de configuración en sus archivos de configuración:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.
 877
Author: eNord9,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-03 00:37:32

Si su versión matplotlib es superior a 1.4, también es posible usar

IPython 3.x y superiores

%matplotlib notebook

import matplotlib.pyplot as plt

Versiones anteriores

%matplotlib nbagg

import matplotlib.pyplot as plt

Ambos activarán el backend nbagg, que habilita la interactividad.

Gráfico de ejemplo con el motor nbagg

 169
Author: Løiten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-22 07:27:29

Ctrl + Enter

%matplotlib inline

Línea mágica: D

Ver: Trazado con Matplotlib.

 70
Author: CodeFarmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-19 10:43:36

No estoy seguro de por qué Joaquín publicó su respuesta como un comentario, pero es la respuesta correcta:

Iniciar ipython con ipython notebook --pylab inline

Editar: Ok, esto ahora está en desuso según el comentario a continuación. Usa la magia % pylab.

 20
Author: foobarbecue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-28 20:03:30

Para hacer que matplotlib esté en línea por defecto en Jupyter (IPython 3):

  1. Editar archivo ~/.ipython/profile_default/ipython_config.py

  2. Añadir línea c.InteractiveShellApp.matplotlib = 'inline'

Tenga en cuenta que agregar esta línea a ipython_notebook_config.py no funcionaría. De lo contrario, funciona bien con Jupyter e IPython 3.1.0

 10
Author: volodymyr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-03 16:03:07

Tengo que estar de acuerdo con foobarbecue (no tengo suficientes recomendaciones para poder simplemente insertar un comentario bajo su post):

Ahora se recomienda que python notebook no se inicie con el argumento --pylab, y según Fernando Pérez (creador de ipythonnb) %matplotlib inline debería ser el comando notebook inicial.

Ver aquí: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

 9
Author: thescoop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-25 21:54:29

Encontré una solución que es bastante satisfactoria. Instalé Anaconda Python y esto ahora funciona fuera de la caja para mí.

 6
Author: Ian Fiske,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-17 00:28:47

En Ubuntu puede eliminar %matplotlib inline siempre que tenga plt.show() después de la creación del gráfico.

 4
Author: Conrad Thiele,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-19 10:44:21

Hice la instalación de anaconda pero matplotlib no está trazando

Comienza a trazar cuando hice esto

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  
 3
Author: Raymond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-12 04:59:58

Puede simular este problema con un error de sintaxis, sin embargo, %matplotlib inline no resolverá el problema.

Primero un ejemplo de la forma correcta de crear un gráfico. Todo funciona como se esperaba con las importaciones y la magia que eNord9 suministró.

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

Sin embargo, al dejar el () fuera del final del tipo de parcela, recibe un no error algo ambiguo.

Código erróneo:

df_randNumbers1.ix[:,["A","B"]].plot.kde

Error de ejemplo:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

Aparte de este mensaje de una línea, no hay seguimiento de pila u otra razón obvia para pensar que cometió un error de sintaxis. La trama no se imprime.

 1
Author: Blake M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:38