subplots用法詳解
我們經常看到這個函數被用了很多次,儘管這個例子只是試圖創建一個圖表.還有其他一些優勢嗎?官方演示subplots() 也用於**f, ax = plt.subplots()**創建單個圖表時,它之後只引用了ax.這是他們使用的代碼.
#Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
plt.subplots()是一個返回包含圖形和軸對象的元組的函數.因此,在使用時fig, ax = plt.subplots(),將此元組解壓縮到變量fig和ax.有fig,如果你想改變人物級別的屬性或保存數字作爲以後的圖像文件是非常有用的(例如用fig.savefig(‘yourfilename.png’).你當然不必使用返回的數字對象,但因此它經常可以看到很多人都用到它.此外,所有軸對象(具有繪圖方法的對象)都具有父圖形對象,因此:
fig, ax = plt.subplots()
比這更簡潔:
fig = plt.figure()
ax = fig.add_subplot(111)
以下問題是如果我想在圖中有更多的子圖?
正如文檔中所提到的,我們可以使用fig = plt.subplots(nrows=2, ncols=2)
在一個圖形對象中設置一組帶有網格(2,2)的子圖.
然後我們知道,fig, ax = plt.subplots()
返回一個元組,讓我們fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
先嚐試一下.
ValueError: not enough values to unpack (expected 4, got 2)
它引發了一個錯誤,但不用擔心,因爲我們現在看到它plt.subplots()實際上返回了一個包含兩個元素的元組.第一個必須是一個圖形對象,另一個應該是一組子圖對象.
那麼讓我們再試一次:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
並檢查類型:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
當然,如果你使用參數(nrows = 1,ncols = 4),那麼格式應該是:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
所以請記住保持列表的構造與我們在圖中設置的子圖網格相同.
如果你有很多子圖怎麼辦?這樣做更容易:fig,axes = plt.subplots(nrows = 10,ncols = 3)
和axes = axes.flatten()
.現在你可以用它的索引來引用每個子圖:axes [0]
,axes [1]
,…
subplots和subplot的區別
可以plt.subplots()一次製作所有子圖,然後將子圖的圖形和軸(複數軸)作爲元組返回。可以將圖形理解爲在其中繪製草圖的畫布。
#create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)
而plt.subplot()如果要單獨添加子圖,則可以使用。它僅返回一個子圖的軸。
fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1)
#(2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)
但是,plt.subplots()首選,因爲它爲您提供了更輕鬆的選項來直接自定義整個圖形
#for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)
但是,使用時plt.subplot(),必須爲每個軸分別指定,這可能會很麻煩。