Matplotlib - 多圖繪製



在本章中,我們將學習如何在同一畫布上建立多個子圖。

subplot() 函式在給定的網格位置返回軸物件。此函式的呼叫簽名為:

plt.subplot(subplot(nrows, ncols, index)

在當前圖形中,該函式在 nrows 行 ncols 列軸的網格的指定位置索引處建立並返回一個 Axes 物件。索引從 1 到 nrows * ncols,以行主序遞增。如果 nrows、ncols 和 index 都小於 10。索引也可以作為單個、連線的、三位數字給出。

例如,subplot(2, 3, 3) 和 subplot(233) 都在當前圖形的右上角建立一個 Axes,佔據圖形高度的一半和圖形寬度的三分之一。

建立子圖將刪除任何與其重疊的先前存在的子圖,超出共享邊界。

import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid with 2 rows and 1 column.
#Since this subplot will overlap the first, the plot (and its axes) previously 
created, will be removed
plt.subplot(211)
plt.plot(range(12))
plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
plt.plot(range(12))

以上程式碼行生成以下輸出:

Multiplots

figure 類的 add_subplot() 函式不會覆蓋現有的繪圖:

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
ax2.plot([1,2,3])

當執行以上程式碼行時,它會生成以下輸出:

Add Spot Function

您可以在同一圖形中新增插入繪圖,方法是在同一圖形畫布中新增另一個軸物件。

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig=plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = np.sin(x)
axes1.plot(x, y, 'b')
axes2.plot(x,np.cos(x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()

執行以上程式碼行後,將生成以下輸出:

Insert Plot
廣告