什么是与IPython魔术函数调用%matplotlib inline等效的纯Python代码?

8
在IPython Notebook中,我定义了一个包含对魔术函数%matplotlib调用的函数,就像这样:
def foo(x):
    %matplotlib inline
    # ... some useful stuff happens in between here
    imshow(np.asarray(img))

我希望将该功能放入Python模块中,以便只需导入并调用它。

但是,为了做到这一点,我需要从我的代码中删除% matplotlib inline 并用其纯Python等效物替换它。

什么是纯Python等效物?


1
pyplot.show 是吗?不太确定你的问题是什么。 - Joran Beasley
你可以通过输入命令'ipython notebook --pylab inline'来启动你的IPython笔记本。 - wrdeman
请不要使用 --pylab 标志,它已经过时并且不再起作用。 - Matt
2个回答

10
%matplotlib inline 直接钩入 IPython 实例。 使用 %hist -t 可以获得相等的结果,它会将处理后的输入显示为纯 Python 代码,这表明 %matplotlib inline 等同于 get_ipython().magic('matplotlib inline'),其中 get_ipython() 返回当前 IPython shell 对象。这是纯 Python 代码,但只能在 IPython 内核中运行。
更深入的解释是,%matplolib xxx 只是将 matplotlib 后端设置为 xxx,而 inline 的情况略有不同,需要首先使用集成在 IPython 中而非 matplotlib 中的后端。即使此后端包含在 matplotlib 中,它也需要在每个单元格执行后触发 IPython 自身的显示和 GC(垃圾回收)功能。

6
嗨,我尝试了这种方法,但返回了“AttributeError: 'NoneType' object has no attribute 'magic'”错误。有帮助吗? - Always_Beginner

-1

我试图注释掉这一行

get_ipython().run_line_magic('matplotlib', 'inline') 

对我来说它是有效的。


2
它如何回答这个问题? - Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接