Python關於%matplotlib inline

在github代碼中經常會看到這樣的代碼:

import numpy
import matplotlib.pyplot as plt
from pandas import read_csv
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
%matplotlib inline

其中最後一句%matplotlib inline比較奇怪,而且無論你是用哪個python的IDE如spyder或者pycharm,這個地方都會報錯,顯示是invalid syntax(無效語法)。那爲什麼代碼裏面還是會有這一句呢?原來是這樣的。
%matplotlib作用

  1. 是在使用jupyter notebook 或者 jupyter qtconsole的時候,纔會經常用到%matplotlib,也就是說那一份代碼可能就是別人使用jupyter notebook 或者 jupyter qtconsole進行編輯的。關於jupyter notebook是什麼,可以參考:[Jupyter Notebook介紹、安裝及使用教程]
  2. 而%matplotlib具體作用是當你調用matplotlib.pyplot的繪圖函數plot()進行繪圖的時候,或者生成一個figure畫布的時候,可以直接在你的python console裏面生成圖像。

而我們在spyder或者pycharm實際運行代碼的時候,可以直接註釋掉這一句,也是可以運行成功的。如下示例:

fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)

plot運行截圖

如圖所示,生成了一個帶座標軸的figure對象,並且畫布顏色是白色的。



作者:hplllrhp
鏈接:https://www.jianshu.com/p/2dda5bb8ce7d
來源:簡書
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章