我试图在MacOS X上使用IPython笔记本,使用Python 2.7.2和IPython 1.1.0。

我无法让matplotlib图形内联显示。

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

我还尝试了%pylab inline和ipython命令行参数——pylab=inline,但这没有什么区别。

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

而不是内联图形,我得到这个:

<matplotlib.figure.Figure at 0x110b9c450>

matplotlib.get_backend()显示我有'模块://IPython.kernel.zmq.pylab。backend_inline的后端。


当前回答

当我在Jupyter的独立单元中运行绘图命令时,我也遇到了同样的问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

通过将绘图命令合并到一个单元格中,问题得到了解决:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

其他回答

我找到了一个相当令人满意的变通办法。我安装了Anaconda Python,现在可以为我开箱即用了。

使用%pylab内联magic命令。

当我在Jupyter的独立单元中运行绘图命令时,我也遇到了同样的问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

通过将绘图命令合并到一个单元格中,问题得到了解决:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

Ctrl + Enter

%matplotlib inline

魔线:D

参见:用Matplotlib绘图。

如果您的matplotlib版本高于1.4,也可以使用它

IPython 3。X及以上

%matplotlib notebook

import matplotlib.pyplot as plt

旧版本

%matplotlib nbagg

import matplotlib.pyplot as plt

两者都将激活nbagg后端,从而支持交互性。