“%matplotlib inline”的用途

2024-04-19 00:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能给我解释一下%matplotlib inline的确切用途吗?


Tags: matplotlibinline用途
3条回答

%matplotlib是IPython中的一个magic function。为了方便阅读,我将引用此处的相关文档:

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

%matplotlib inlinesets the backend of matplotlib to the 'inline' backend

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

使用“内联”后端时,matplotlib图形将包含在笔记本中的代码旁边。还值得阅读How to make IPython notebook matplotlib plot inline以了解如何在代码中使用它。

如果还需要交互,可以将nbagg backend%matplotlib notebook一起使用(在IPython 3.x中),如here所述。

如果您正在运行IPython,%matplotlib inline将使打印输出显示出来并存储在笔记本中。

根据documentation

To set this up, before any plotting or import of matplotlib is performed you must execute the %matplotlib magic command. This performs the necessary behind-the-scenes setup for IPython to work correctly hand in hand with matplotlib; it does not, however, actually execute any Python import commands, that is, no names are added to the namespace.

A particularly interesting backend, provided by IPython, is the inline backend. This is available only for the Jupyter Notebook and the Jupyter QtConsole. It can be invoked as follows:

%matplotlib inline

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

如果要将绘图添加到Jupyter笔记本,则%matplotlib inline是标准解决方案。还有其他的魔法命令将在Jupyter中交互使用matplotlib

%matplotlib:任何plt绘图命令现在都会打开一个图形窗口,可以运行进一步的命令来更新绘图。某些更改不会自动绘制,若要强制更新,请使用plt.draw()

%matplotlib notebook:将生成嵌入笔记本中的交互式绘图,您可以缩放和调整图形大小

%matplotlib inline:仅在笔记本中绘制静态图像

相关问题 更多 >