天天看點

plt.subplot()使用方法以及參數介紹

plt.subplot()

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

  1. 第一個參數:*args (官網文檔描述)

    Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right.

    可以使用三個整數,或者三個獨立的整數來描述子圖的位置資訊。如果三個整數是行數、列數和索引值,子圖将分布在行列的索引位置上。索引從1開始,從右上角增加到右下角。

    pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.

    位置是由三個整型數值構成,第一個代表行數,第二個代表列數,第三個代表索引位置。舉個列子:plt.subplot(2, 3, 5) 和 plt.subplot(235) 是一樣一樣的。需要注意的是所有的數字不能超過10。

  2. 第二個參數:projection : {None, ‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’, str}, optional

    The projection type of the subplot (Axes). str is the name of a costum projection, see projections. The default None results in a ‘rectilinear’ projection.

    可選參數:可以選擇子圖的類型,比如選擇polar,就是一個極點圖。預設是none就是一個線形圖。

  3. 第三個參數:polar : boolean, optional

    If True, equivalent to projection=‘polar’. 如果選擇true,就是一個極點圖,上一個參數也能實作該功能。

    官方文檔傳送門:plt.subplot()

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 2, 2)
y1 = np.sin(x)

y2 = np.cos(x)

ax1 = plt.subplot(2, 2, 1, frameon = False) # 兩行一列,位置是1的子圖
plt.plot(x, y1, 'b--')
plt.ylabel('y1')
ax2 = plt.subplot(2, 2, 2, projection = 'polar')
plt.plot(x, y2, 'r--')
plt.ylabel('y2')
plt.xlabel('x')
plt.subplot(2, 2, 3, sharex = ax1, facecolor = 'red')
plt.plot(x, y2, 'r--')
plt.ylabel('y2')

plt.show()
           

以上代碼畫圖如下:

plt.subplot()使用方法以及參數介紹

可以看到plt.subplot()可以依次畫出這些子圖,優點是簡單明了,缺點是略顯麻煩。