python使用matplotlib在一個圖形中繪制多個子圖以及一個子圖中繪制多條動態折線問題


  在講解繪制多個子圖之前先簡單了解一下使用matplotlib繪制一個圖,導入繪圖所需庫matplotlib並創建一個等間隔的列表x,將[0,2*pi]等分為50等份,繪制函數sin(x)。當沒有給定x軸數值時,默認以下標作為x的值,如果x值確定,則繪圖時寫為 plt.plot(x,y)

  如若想要繪制一個圖時寫入標簽,則寫為 plt.plot(x,y,label="figure1")

from numpy import *
import matplotlib.pyplot as plt 
x = linspace(0, 2 * pi, 50)
plt.plot(sin(x))
plt.xlabel('x-label')
plt.ylabel('y-label', fontsize='large')
plt.title('title')

以下先將整體代碼插入,再分布講解:

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 

def minmax_value(list1):
    minvalue=min(list1)
    maxvalue=max(list1)
    return minvalue,maxvalue

plt.figure(figsize=(16,14),dpi=98)
xmajorLocator = MultipleLocator(1) #將x主刻度標簽設置為1的倍數

plt.rcParams['font.sans-serif']=['SimHei']  
plt.rcParams['axes.unicode_minus'] = False

p1 = plt.subplot(121)
p2 = plt.subplot(122)


#圖中展示點的數量
pointcount=5

x=[i for i in range(20)]
print(x)

y1=[i**2 for i in range(20)]
y2=[i*4 for i in range(20)]
y3=[i*3+2 for i in range(20)]
y4=[i*4 for i in range(20)]

for i in range(len(x)-1):
    if i<pointcount:
        minx,maxx=minmax_value(x[:pointcount])
        minx,maxx=minmax_value(x[:pointcount])
        minyA,maxyA=minmax_value(y1[:pointcount])
        minyB,maxyB=minmax_value(y2[:pointcount])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p1.axis([minx,maxx,miny1,maxy1])
        p1.grid(True)
        A,=p1.plot(x[:pointcount],y1[:pointcount],"g-")
        B,=p1.plot(x[:pointcount],y2[:pointcount],"b-")

        #設置主刻度標簽的位置,標簽文本的格式
        p1.xaxis.set_major_locator(xmajorLocator)
        legend=p1.legend(handles=[A,B],labels=["圖1","圖2"])    
        
        
        minx,maxx=minmax_value(x[:pointcount])
        minx,maxx=minmax_value(x[:pointcount])
        minyA,maxyA=minmax_value(y3[:pointcount])
        minyB,maxyB=minmax_value(y4[:pointcount])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p2.axis([minx,maxx,miny1,maxy1])
        p2.grid(True)
        A,=p2.plot(x[:pointcount],y3[:pointcount],"r-")
        B,=p2.plot(x[:pointcount],y4[:pointcount],"y-")

        #設置主刻度標簽的位置,標簽文本的格式
        p2.xaxis.set_major_locator(xmajorLocator)
        legend=p2.legend(handles=[A,B],labels=["圖3","圖4"])  
    elif i>=pointcount:
        minx,maxx=minmax_value(x[i-pointcount:i])
        minx,maxx=minmax_value(x[i-pointcount:i])
        minyA,maxyA=minmax_value(y1[i-pointcount:i])
        minyB,maxyB=minmax_value(y2[i-pointcount:i])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p1.axis([minx,maxx,miny1,maxy1])
        p1.grid(True)
        A,=p1.plot(x[i-pointcount:i],y1[i-pointcount:i],"g-")
        B,=p1.plot(x[i-pointcount:i],y2[i-pointcount:i],"b-")

        #設置主刻度標簽的位置,標簽文本的格式
        p1.xaxis.set_major_locator(xmajorLocator)
        legend=p1.legend(handles=[A,B],labels=["圖1","圖2"])

        minx,maxx=minmax_value(x[i-pointcount:i])
        minx,maxx=minmax_value(x[i-pointcount:i])
        minyA,maxyA=minmax_value(y3[i-pointcount:i])
        minyB,maxyB=minmax_value(y4[i-pointcount:i])
        
        maxy1=max(maxyA,maxyB)
        miny1=min(minyA,minyB)
        p2.axis([minx,maxx,miny1,maxy1])
        p2.grid(True)
        A,=p2.plot(x[i-pointcount:i],y3[i-pointcount:i],"r-")
        B,=p2.plot(x[i-pointcount:i],y4[i-pointcount:i],"y-")

        #設置主刻度標簽的位置,標簽文本的格式
        p2.xaxis.set_major_locator(xmajorLocator)
        legend=p2.legend(handles=[A,B],labels=["圖3","圖4"])


    p1.set_xlabel("橫軸屬性名一",fontsize=14)
    p1.set_ylabel("縱軸屬性名一",fontsize=14)
    p1.set_title("主題一",fontsize=18)
    
    p2.set_xlabel("橫軸屬性名二",fontsize=14)
    p2.set_ylabel("縱軸屬性名二",fontsize=14)
    p2.set_title("主題二",fontsize=18)


    plt.pause(0.3)
    plt.tight_layout(pad=4, w_pad=4.0, h_pad=3.0) 

運行結果為:

1、導入庫

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 

2、由於繪圖過程中多次使用獲取最大最小值,將獲取最大最小值寫入函數,后面直接調用函數即可。

def minmax_value(list1):
    minvalue=min(list1)
    maxvalue=max(list1)
    return minvalue,maxvalue

3、(1)創建自定義圖像,並設置figured的長和寬以及dpi參數指定繪圖對象的分辨率;(2)設置x軸刻度的間隔;(3)對本次繪圖中的字體進行設置;(4)在matplotlib下,一個figure對象可以包含多個子圖(Axes),使用subplot()快速繪制。

plt.figure(figsize=(16,14),dpi=98)

xmajorLocator = MultipleLocator(1)
plt.rcParams['font.sans-serif']=['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False
 
p1 = plt.subplot(121)
p2 = plt.subplot(122)

4、當數據量過多時,對數據一次性展示不能夠達到對數據內部信息的解讀。本例采用一次展示其中一部分數據,並動態的更新圖片,於此同時,動態更新橫縱坐標軸的取值范圍。下面代碼首先設置了每次展示點的數量,並獲取了主題一中的所有數據值。根據x取值范圍和值域y獲取當前繪圖過程中的橫縱坐標取值范圍,最后根據x,y的值進行繪圖。

下面將先在一個子圖上顯示兩條靜態折現。當使用動態的折線圖時,只需動態更新數據和橫縱坐標的取值范圍。總體代碼中已經寫出,下面不再贅述。

#圖中展示點的數量
pointcount=5
x=[i for i in range(20)]

y1=[i**2 for i in range(20)]
y2=[i*4 for i in range(20)]

minx,maxx=minmax_value(x[:pointcount])
minyA,maxyA=minmax_value(y1[:pointcount])
minyB,maxyB=minmax_value(y2[:pointcount])
        
maxy1=max(maxyA,maxyB)
miny1=min(minyA,minyB)
p1.axis([minx,maxx,miny1,maxy1])
p1.grid(True)#繪圖過程中出現的網格設置 A,
=p1.plot(x[:pointcount],y1[:pointcount],"g-") B,=p1.plot(x[:pointcount],y2[:pointcount],"b-")

#設置主刻度標簽的位置,標簽文本的格式
p1.xaxis.set_major_locator(xmajorLocator)
legend=p1.legend(handles=[A,B],labels=["圖1","圖2"])  

結果如下所示:

5、設置邊界,不設置邊界經常會因為橫縱軸的字體太大等其他原因導致橫縱軸或者標題只能顯示其中一部分。

plt.tight_layout(pad=4, w_pad=4.0, h_pad=3.0) 

 如有問題,歡迎批評指正,謝謝。


免責聲明!

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



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