什么是纯 Python 等效于 IPython 魔术函数调用 %matplotlib inline?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28724610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:39:45  来源:igfitidea点击:

What is the pure Python equivalent to the IPython magic function call %matplotlib inline?

pythonmatplotlibipython-notebook

提问by coffee-grinder

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

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

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

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

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

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

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

What is the pure-Python equivalent?

什么是纯 Python 等价物?

采纳答案by Matt

%matplotlib inlinedirectly hook into IPython instance. You can get the equivalent by using %hist -tthat show you the processed input as pure python, which show that %matplotlib inlineis 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.

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

For more in depth explanation, %matplolib xxxjust 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.

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

回答by Darshana Singh

I tried to comment out this line

我试图注释掉这一行

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

and it worked for me.

它对我有用。