【问题标题】:Plot an IPython Notebook figure inline with fig.show()?用 fig.show() 内联绘制一个 IPython Notebook 图形?
【发布时间】:2013-03-06 23:59:01
【问题描述】:

我正在使用 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

【问题讨论】:

  • 你试过Ipython的显示功能吗?据我所知,这是“官方”方法
  • 是不想生成图形,还是不想看空坐标轴?
  • 一般来说,我想在一个单元格中创建一个图形,然后使用它的句柄在另一个单元格中处理它,然后推迟显示它,直到稍后再显示一个不同的单元格。
  • 如果发布的两个答案中的任何一个解决了您的问题,请接受它(左侧的大复选标记)。

标签: python-2.7 matplotlib ipython ipython-notebook


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。这也意味着 display(fig) 会这样做。
【解决方案2】:

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

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.

不过,如果单元格的最后一行返回一个 fig 对象,IPython 仍会显示该图形,您可以通过以 ; 结束它或添加 pass 作为最后一行来避免这种情况。

【讨论】:

  • c.InlineBackend.close_figures = False 现在在 \myIPythonDir\profile_myHomeProfile\ipython_notebook_config.py 中设置。 axes = fig.add_axes([0, 0, 1, 1]) cmd 仍然在单元格之后给我一个图,即使使用分号并通过。有什么方法可以查看当前选项以检查是否确实设置了此标志?
  • %config InlineBackend 应该告诉你不同的配置值。
  • 这个几乎可以用了!我只是无法在中间单元格中得到数字,即使用 ;或通过
  • 将 matplotlib 交互设置为 false ? matplotlib.ioff()IIRC。
【解决方案3】:

使用较新的

  • 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

应该够了。请看下面的截图

注意带有matplotlib.pyplot.ioff() 和类似内容的建议不起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2015-06-16
    • 2013-01-01
    • 2014-02-17
    • 2014-02-02
    • 2013-12-26
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多