使用matplotlib.pyplot中的三種方法畫子圖


本文所用包:

from matplotlib import pyplot as plt

import numpy as np

此文主要記錄使用matplotlib.pyplot中的三個函數,主要結合代碼展示效果:

 

一、plt.subplots

實例代碼:

 1 from matplotlib import pyplot as plt
 2 import numpy as np
 3 
 4 x = np.linspace(1, 100, num= 25, endpoint = True)
 5 
 6 def y_subplot(x,i):
 7     return np.cos(i * np.pi *x)
 8 
 9 #使用subplots 畫圖
10 f, ax = plt.subplots(2,2)
11 #type(f) #matplotlib.figure.Figure
12 
13 style_list = ["g+-", "r*-", "b.-", "yo-"]
14 ax[0][0].plot(x, y_subplot(x, 1), style_list[0])
15 ax[0][1].plot(x, y_subplot(x, 2), style_list[1])
16 ax[1][0].plot(x, y_subplot(x, 3), style_list[2])
17 ax[1][1].plot(x, y_subplot(x, 4), style_list[3])
18 
19 plt.show()

注釋:使用subplots會返回兩個東西,一個是matplotlib.figure.Figure,也就是f,另一個是Axes object or array of Axes objects,也就是代碼中的ax;

把f理解為你的大圖,把ax理解為包含很多小圖對象的array;所以下面的代碼就使用ax[0][0]這種從ax中取出實際要畫圖的小圖對象;畫出的圖如下所示;

二、plt.subplot;

實例代碼:

#使用subplot畫圖
for i in  range(1,5):
    plt.subplot(2,2,i)
    plt.plot(x, y_subplot(x,i), style_list[i- 1])
plt.show()

plt.subplot函數的第一個參數和第二個參數分別制定了子圖有幾列和幾行;這個和subplots的參數意思相同;第三個參數就是指定在那個子圖上畫圖的順序,分別是從左往右;慢慢體味subplot和subplots的區別吧;subplot方法畫的圖如下所示:

 

三、plt.add_subplots

實例代碼:

fig = plt.figure()
for i in range(1,5):
    ax = fig.add_subplot(2,2,i)
    ax.plot(x, y_subplot(x,i), style_list[i -1])

plt.show()

add_subplot函數也就是向Figure畫板中添加每一個子圖

畫出的圖形如下所示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM