2017-03-26 13 views
79

有人可以向我解釋什麼是%matplotlib inline的使用情況?「%matplotlib內聯」的用途

+1

它是一種神奇的功能呈現在筆記本該圖(而不是顯示所述圖形對象的轉儲)。一個簡單的Matplotlib教程可以在這裏找到https://www.data-blogger.com/2017/11/15/python-matplotlib-pyplot-a-perfect-combination/。 –

回答

67

%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所述。

+1

%matplotlib inline ^ SyntaxError:無效的語法 –

+0

@Jadda你在使用IPython嗎?如果不是的話,你會得到一個語法錯誤,因爲它不是有效的CPython(Python的'標準'解釋器)。無論如何,除非你使用IPython筆記本,否則沒什麼用處,因爲整個問題是用筆記本內聯繪圖。 – Aurora0001

+0

是的。我在Spyder IDE(Anaconda的一部分)中使用它來實現Tensorflow對象檢測API –

17

假設您正在運行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.