用fig.show()内联一个IPython Notebook图形?

时间:2013-03-18 15:21:30

标签: python-2.7 matplotlib ipython ipython-notebook

我正在使用;

调用IPython Notebook的内联模式
%pylab inline

以下代码会立即在单元格中绘制一个数字;

fig = plt.figure()
axes = fig.add_axes([0, 0, 1, 1])

但是我想在一个单元格中创建绘图/轴等,稍后使用可能的绘图;

fig.show()

如何获得对内联模式的更多控制?如果我不使用%pylab inline,它会在一个我不想要的单独窗口中创建绘图(并且它通常会冻结窗口)。

版本;

Numpy: 1.7.0
Matplotlib: 1.2.1rc1
Python: 2.7.2 (default, Jun 24 2011, 12:22:14) [MSC v.1500 64 bit (AMD64)]
Pandas: 0.10.1
PyLab: 1.7.0

3 个答案:

答案 0 :(得分:5)

您可能正在寻找禁用自动关闭数据:

InlineBackend options
---------------------
--InlineBackend.close_figures=<CBool>
    Default: True
Close all figures at the end of each cell.
When True, ensures that each cell starts with no active figures, but it also
means that one must keep track of references in order to edit or redraw
figures in subsequent cells. This mode is ideal for the notebook, where
residual plots from other cells might be surprising.
When False, one must call figure() to create new figures. This means that
gcf() and getfigs() can reference figures created in other cells, and the
active figure can continue to be edited with pylab/pyplot methods that
reference the current active figure. This mode facilitates iterative editing
of figures, and behaves most consistently with other matplotlib backends,
but figure barriers between cells must be explicit.

仍然,如果单元格的最后一行返回一个无花果对象,IPython将显示该数字,你可以通过用;结尾或添加pass作为最后一行来避免这种情况。

答案 1 :(得分:5)

所以我猜你想要的是这个:

from matplotlib.backends.backend_agg import FigureCanvasAgg as fc
fig = Figure()
canvas = fc(fig)
ax = fig.add_subplot(1, 1, 1)
ax.plot(arange(10))

要在另一个单元格中显示绘图,只需使用:

fig

答案 2 :(得分:1)

使用更新的

  • Jupyter:4.6
  • Jupyter笔记本电脑:6.0
  • Matplotlib:3.1
  • ipykernel:5.1

您真正需要做的就是用matplotlib.pyplot.Figure(在一个单元格中)创建图形,然后将该图形作为另一个单元格中的值。例如

在单元格[1]

%matplotlib inline 

在单元格[2]

from matplotlib.pyplot import Figure
from numpy import arange 
from numpy.random import normal 

fig = Figure()
ax  = fig.add_subplot(111)

ax.plot(arange(10),normal(size=10),label='Data')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.legend();

最后在单元格[3]

fig

那应该足够了。请参见下面的屏幕截图

Screenshot

使用matplotlib.pyplot.ioff()及类似的注释建议不起作用