什么是纯 Python 等效于 IPython 魔术函数调用 %matplotlib inline? [英] What is the pure Python equivalent to the IPython magic function call %matplotlib inline?

查看:36
本文介绍了什么是纯 Python 等效于 IPython 魔术函数调用 %matplotlib inline?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 IPython Notebook 中,我定义了一个包含对魔术函数 %matplotlib 的调用的函数,如下所示:

In IPython Notebook, I defined a function that contains a call to the magic function %matplotlib, like this:

def foo(x):
    %matplotlib inline
    # ... some useful stuff happens in between here
    imshow(np.asarray(img))

我想将该函数放入 Python 模块中,以便我可以导入和调用它.

I'd like to put that function into a Python module so that I can just import and call it.

但是,要做到这一点,我需要从我的代码中删除 %matplotlib inline 并将其替换为纯 Python 等效项.

However, to do this, I'd need to remove the %matplotlib inline from my code and replace it with its pure-Python equivalent.

纯 Python 的等价物是什么?

What is the pure-Python equivalent?

推荐答案

%matplotlib inline 直接钩入 IPython 实例.您可以通过使用 %hist -t 来获得等效的结果,将处理后的输入显示为纯 python,这表明 %matplotlib inline 等效于 get_ipython().magic('matplotlib inline') 其中 get_ipython() 返回当前的 ipython shell 对象.它是纯 python,但只能在 IPython 内核中工作.

%matplotlib inline directly hook into IPython instance. You can get the equivalent by using %hist -t that show you the processed input as pure python, which show that %matplotlib inline is equivalent to get_ipython().magic('matplotlib inline') in which get_ipython() return the current ipython shell object. It is pure python but will work only in an IPython kernel.

为了更深入的解释,%matplolib xxx 只需将 matplotlib 后端设置为 xxx,情况 od inline 有点不同,首先需要一个随 IPython 一起提供的后端,而不是 matplotlib.即使这个后端在 matplotlib 本身中,它也需要在 IPython 本身中使用钩子来触发每个单元格执行后 matplotlib 图形的显示和 GC.

For more in depth explanation, %matplolib xxx just set matplotlib backend to xxx, the case od inline is a bit different and requires first a backend which is shipped with IPython and not matplotlib. Even if this backend was in matplotlib itself, it needs hooks in IPython itself to trigger the display and GC of matplotlib figures after each cell execution.

这篇关于什么是纯 Python 等效于 IPython 魔术函数调用 %matplotlib inline?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆