Python matplotlib(2D繪圖庫)

matplotlib簡介

matplotlib是python最著名的繪圖庫,它提供了一整套和matlab相似的命令API,十分適合交互式地進行製圖。而且也可以方便地將它作爲繪圖控件,嵌入GUI應用程序中。它的文檔相當完備,並且Gallery頁面 中有上百幅縮略圖,打開之後都有源程序。因此如果你需要繪製某種類型的圖,只需要在這個頁面中瀏覽/複製/粘貼一下,基本上都能搞定。

在Linux下比較著名的數據圖工具還有gnuplot,這個是免費的,Python有一個包可以調用gnuplot,但是語法比較不習慣,而且畫圖質量不高。而Matplotlib則比較強:Matlab的語法、python語言、latex的畫圖質量(還可以使用內嵌的latex引擎繪製的數學公式)。

Matplotlib 圖像各個部分
(1)Figure:整個圖像爲一個Figure對象。一個Figure對象可以包含一個或者多個Axes子圖。

(2)Axes:每個Axes(ax)對象都是一個擁有自己座標系統的繪圖區域。子圖Axes可以用subplot()快速繪製。
各個對象關係可以梳理成以下內容:
圖像中所有對象均來自於Artist的基類。

當前的圖表和子圖可以使用plt.gcf()和plt.gca()獲得,分別表示Get Current Figure和Get Current Axes。

matplotlib.pyplot
matplotlib.pyplot(下面簡寫成plt)是一些命令行風格函數的集合,使matplotlib以類似於MATLAB的方式工作。每個plt函數對一幅圖片(figure)做一些改動:比如創建新圖片,在圖片創建一個新的作圖區域(plotting area),在一個作圖區域內畫直線,給圖添加標籤(label)等。plt是有狀態的,亦即它會保存當前圖片和作圖區域的狀態,新的作圖函數會作用在當前圖片的狀態基礎之上。

plt可在圖片上做的一些修改如下:
(1)plt.axis:座標軸

plt.axis([0,6,0,20])
axis()函數接受形如[xmin,xmax,ymin,ymax]的參數,指定了X,Y軸座標的範圍。

(2)Tick:刻度線,Tick Label:刻度註釋 plt.xticks(np.linspace(-1, 1, 5)) #x座標爲從-1到1平均分成五個點:-1,-0.5,0.5,1
(3)plt.xlabel,plt.ylabel:座標軸標註
(4)plt.title:圖像標題
plt.title(s, *args, **kwargs)
爲當前圖表添加標題,重要參數如下:
s:標題內容
fontdict:標題樣式,是一個字典
loc:標題位置,可選 ‘centet’, ‘left’, ‘right’

(5)plt.legend():顯示圖例

座標軸相關設置

plt.axis():座標軸設置

函數
plt.axis(*v, **kwargs)

主要用於設置座標軸的屬性,返回值爲當前的座標軸範圍 [xmin, xmax, ymin, ymax],幾種調用方式如下:

調用方式 說明
axis() 返回當前的座標軸範圍 [xmin, xmax, ymin, ymax]
axis(v) 其中 v 爲 [xmin, xmax, ymin, ymax]用來設置座標軸範圍
axis(‘off’) 不顯示座標軸和座標軸名稱
axis(‘equal’) x、y軸對應長度所表示的數值相同,提高某一個軸的範圍以保持圖表大小及比例不變
axis(‘scaled’) x、y 軸對應長度所表達的數值相同,並保持兩個軸的數值範圍不變,因此需要對圖表比例進行調整(縮放)
axis(‘tight’) 在顯示所有數據的前提下,儘量減少兩個軸的數值範圍,並儘量讓數據居中
axis(‘image’) 將圖表比例按照圖片的比例進行調整(縮放)
axis(‘square’) 將圖表變成正方形,並確保 (xmax-xmin) 與 (ymax-ymin) 相同
axis(‘auto’) 恢復自動範圍
plt.xlim() 和 plt.ylim():x和y軸數值範圍

設置並返回 x 軸和 y 軸的數值範圍,以 xlim() 爲例說明調用方式:

調用方式 說明
xlim() 返回 xmin, xmax
xlim(xmin, xmax) 或 xlim((xmin, xmax)) 設置 x 軸的最大、最小值
xlim(xmax = n) 和 xlim(xmin = n) 設置 x 軸的最大或最小值
plt.xlabel()和plt.ylabel:x軸及y軸的標籤

函數
plt.xlabel(label, fontdict=None, labelpad=None, **kwargs)

plt.xticks()和plt.yticks():x軸及y軸刻度

plt.xticks(locs, [labels], **kwargs) # Set locations and labels
locs表示位置,labels決定這些位置上的標籤,labels的默認值爲和locs相同。

# --coding:utf-8--
import matplotlib.pyplot as plt

數據設置

x1 = [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y1 = [0, 223, 488, 673, 870, 1027, 1193, 1407, 1609, 1791, 2113, 2388];

x2 = [0, 5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000];
y2 = [0, 214, 445, 627, 800, 956, 1090, 1281, 1489, 1625, 1896, 2151];

設置輸出的圖片大小

figsize = 7,5
figure, ax = plt.subplots(figsize=figsize)

在同一幅圖片上畫兩條折線

A, = plt.plot(x1, y1, ‘-r’, label=‘A’, linewidth=5.0)
B, = plt.plot(x2, y2, ‘b-.’, label=‘B’, linewidth=5.0)

設置圖例並且設置圖例的字體及大小

font1 = {‘family’: ‘Times New Roman’,
‘weight’: ‘normal’,
‘size’: 23,
}
legend = plt.legend(handles=[A, B], prop=font1)

設置座標刻度值的大小以及刻度值的字體

plt.tick_params(labelsize=23)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname(‘Times New Roman’) for label in labels]

設置橫縱座標的名稱以及對應字體格式

font2 = {‘family’: ‘Times New Roman’,
‘weight’: ‘normal’,
‘size’: 30,
}
plt.xlabel(‘round’, font2)
plt.ylabel(‘value’, font2)

將文件保存至文件中並且畫出圖

plt.savefig(‘figure.eps’)
plt.show()

    plt.figure()的使用

    函數

    plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)

    重要參數

    • num:圖像編號或名稱,數字爲編號 ,字符串爲名稱
    • figsize:指定figure的寬和高,單位爲英寸;
    • dpi:指定繪圖對象的分辨率,即每英寸多少個像素,缺省值爲80 1英寸等於2.5cm,A4紙是 21*30cm的紙張
    • facecolor:背景顏色
    • edgecolor:邊框顏色
    • frameon:是否顯示邊框

    例子1

    import matplotlib.pyplot as plt
    創建自定義圖像
    fig=plt.figure(figsize=(4,3),facecolor='blue')
    plt.show()
    
      subplot創建單個子圖

      matplotlib下, 一個 Figure 對象可以包含多個子圖(Axes), 可以使用 subplot() 快速繪製, 其調用形式如下 :
      subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)

      • 圖表的整個繪圖區域被分成 numRows 行和 numCols 列
      • 然後按照從左到右,從上到下的順序對每個子區域進行編號,左上的子區域的編號爲1
      • plotNum 參數指定創建的Axes對象所在的區域

      例如,如果 numRows = 2, numCols = 2, 那整個繪製圖表樣式爲 2X2 的圖片區域, 用座標表示爲
      (1, 1), (1, 2)
      (2, 1), (2, 2)
      這時, 當 plotNum = 2時,表示的座標爲(1, 2), 即第一行第二列的子圖

      (1)如果 numRows, numCols 和 plotNum 這三個數都小於 10 的話, 可以把它們縮寫爲一個整數, 例如 subplot(222) 和 subplot(2,2,2) 是相同的。
      (2)subplot在 plotNum 指定的區域中創建一個軸對象. 如果新創建的軸和之前創建的軸重疊的話,之前的軸將被刪除。

      示例1
      規則劃分成2*2的

      import matplotlib.pyplot as plt
      

      plt.figure()

      繪製第一個圖

      plt.subplot(2, 2, 1)
      plt.plot([0, 1], [0, 1])

      繪製第二個圖

      plt.subplot(2, 2, 2)
      plt.plot([0, 1], [0, 1])

      繪製第三個圖

      plt.subplot(2, 2, 3)
      plt.plot([0, 1], [0, 1])

      繪製第四個圖

      plt.subplot(2, 2, 4)
      plt.plot([0, 1], [0, 1])
      a,b,c,d=plt.axis()
      print(“a:”,a," b:",b," c:"," d:",d) #a: -0.05 b: 1.05 c: d: 1.05
      plt.show()

        不規則的

        import matplotlib.pyplot as plt
        

        plt.figure()

        繪製第一個圖

        plt.subplot(2, 1, 1)
        plt.plot([0, 1], [0, 1])

        繪製第二個圖

        plt.subplot(2, 3, 4)
        plt.plot([0, 1], [0, 1])

        繪製第三個圖

        plt.subplot(2, 3, 5)
        plt.plot([0, 1], [0, 1])

        繪製第四個圖

        plt.subplot(2, 3, 6)
        plt.plot([0, 1], [0, 1])
        plt.show()

          import matplotlib.pyplot as plt
          import numpy as np
          

          def f(t):
          return np.exp(-t) * np.cos(2 * np.pi * t)

          t1 = np.arange(0, 5, 0.1)
          t2 = np.arange(0, 5, 0.02)

          plt.figure(12)#12代表第幾個figure(左上角)

          分成2x2,佔用第一個,即第一行第一列的子圖

          plt.subplot(221)
          plt.plot(t1, f(t1), ‘bo’, t2, f(t2), ‘r–’)

          分成2x2,佔用第二個,即第一行第二列的子圖

          plt.subplot(222)
          plt.plot(t2, np.cos(2 * np.pi * t2), ‘r–’)

          將整個Figure,分成2x1,佔用第二個,即第二行

          plt.subplot(212)
          plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

          plt.show()

            subplots創建多個子圖

            subplots參數與subplots相似。兩者都可以規劃figure劃分爲n個子圖,但每條subplot命令只會創建一個子圖,而一條subplots就可以將所有子圖創建好。subplots返回一個 Figure實例fig 和一個 AxesSubplot實例ax 。
            fig, ax = plt.subplots()

            import numpy as np
            import matplotlib.pyplot as plt
            

            x = np.arange(0, 100)

            劃分子圖

            fig, axes = plt.subplots(2, 2) #2行2列
            ax1 = axes[0, 0]
            ax2 = axes[0, 1]
            ax3 = axes[1, 0]
            ax4 = axes[1, 1]

            作圖1

            ax1.plot(x, x)

            作圖2

            ax2.plot(x, -x)

            作圖3

            ax3.plot(x, x ** 2)
            ax3.grid(color=‘r’, linestyle=’–’, linewidth=1, alpha=0.3)

            作圖4

            ax4.plot(x, -2xx+2*x)
            plt.savefig(“test.jpg”)
            plt.show()

              add_subplot與add_axes新增子圖或區域
              import matplotlib.pyplot as plt
              import numpy as np
              

              def f(t):
              return np.exp(-t) * np.cos(2 * np.pi * t)

              t1 = np.arange(0, 5, 0.1)
              t2 = np.arange(0, 5, 0.02)
              #使用add方式
              fig=plt.figure(12)#12代表第幾個figure(左上角)

              分成2x2,佔用第一個,即第一行第一列的子圖

              ax1=fig.add_subplot(221)
              ax1.plot(t1, f(t1), ‘bo’, t2, f(t2), ‘r–’)

              分成2x2,佔用第二個,即第一行第二列的子圖

              ax2=fig.add_subplot(222)
              ax2.plot(t2, np.cos(2 * np.pi * t2), ‘r–’)

              將整個Figure,分成2x1,佔用第二個,即第二行

              ax3=fig.add_subplot(212)
              ax3.plot([1, 2, 3, 4], [1, 4, 9, 16])

              plt.show()

                plt.legend:畫圖例

                1.使用pyplot的方式
                legend語法參數如下: matplotlib.pyplot.legend(*args,**kwargs)
                一些重要參數如下:
                (1)設置圖例位置
                使用loc參數
                plt.legend(loc=‘lower left’)
                有下面一些組合:
                ‘best’ : 0, (only implemented for axes legends)(自適應方式) ‘upper right’ : 1, ‘upper left’ : 2, ‘lower left’ : 3, ‘lower right’ : 4, ‘right’ : 5, ‘center left’ : 6, ‘center right’ : 7, ‘lower center’ : 8, ‘upper center’ : 9, ‘center’ : 10

                (2)設置圖例字體
                #設置字體大小
                fontsize: int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

                (3)設置圖例邊框及背景
                plt.legend(loc=‘best’,frameon=False) #去掉圖例邊框
                plt.legend(loc=‘best’,edgecolor=‘blue’) #設置圖例邊框顏色
                plt.legend(loc=‘best’,facecolor=‘blue’) #設置圖例背景顏色,若無邊框,參數無效

                (4)設置圖例標題
                plt.legend(loc=‘best’,title=‘figure 1 legend’)

                2.使用面向對象的方式
                (1)獲取並設置legend圖例

                plt.legend(loc=0, numpoints=1)  
                leg = plt.gca().get_legend() #或leg=ax.get_legend()  
                ltext = leg.get_texts()  
                plt.setp(ltext, fontsize=12,fontweight='bold') 
                

                  (2)設置圖例

                  legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')  
                  legend.get_frame().set_facecolor('red')   #設置圖例legend背景爲紅色  
                  frame = legend.get_frame()  
                  frame.set_alpha(1)  
                  frame.set_facecolor('none') #設置圖例legend背景透明  
                  

                    (3)移除圖例
                    ax1.legend_.remove() ##移除子圖ax1中的圖例

                    示例1:顯示多圖例legend

                    import matplotlib.pyplot as plt
                    import numpy as np
                    

                    x = np.random.uniform(-1, 1, 4)
                    y = np.random.uniform(-1, 1, 4)
                    p1, = plt.plot([1, 2, 3])
                    p2, = plt.plot([3, 2, 1])
                    l1 = plt.legend([p2, p1], [“line 2”, “line 1”], loc=‘upper left’)

                    p3 = plt.scatter(x[0:2], y[0:2], marker=‘D’, color=‘r’)
                    p4 = plt.scatter(x[2:], y[2:], marker=‘D’, color=‘g’)

                    This removes l1 from the axes.

                    plt.legend([p3, p4], [‘label’, ‘label1’], loc=‘lower right’, scatterpoints=1)

                    Add l1 as a separate artist to the axes

                    plt.gca().add_artist(l1)
                    plt.show()

                      示例2:

                      import matplotlib.pyplot as plt
                      #藍線
                      line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
                      #橘黃色的線
                      line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
                      # 爲第一個線條創建圖例
                      first_legend = plt.legend(handles=[line1], loc=1)
                      # plt.gca(): 返回當前axes(matplotlib.axes.Axes)
                      # plt.gcf(): 返回當前figure(matplotlib.figure.Figure)
                      # plt.clf(): 清理當前figure
                      # plt.cla(): 清理當前axes
                      # plt.close(): 一副figure知道顯示的調用close()時纔會釋放她所佔用的資源;
                      # 手動將圖例添加到當前軸域
                      ax = plt.gca().add_artist(first_legend)
                      # 爲第二個線條創建另一個圖例
                      plt.legend(handles=[line2], loc=4)
                      plt.show()
                      

                        plt.plot:曲線圖、折線圖

                        plt.plot畫圖時可以設定線條參數。包括:顏色、線型、標記風格。

                        只提供一個列表或數組(Y向量)-缺省x
                        如果只提供給plot()函數一個列表或數組,matplotlib會認爲這是一串Y值(Y向量),並且自動生成X值(X向量),x的默認值是:range(len(y))

                        import matplotlib.pyplot as plt
                        plt.plot([1,2,3,4])
                        plt.ylabel('some numbers')
                        plt.show()
                        

                          提供X,Y向量
                          也可以給plt.plot()函數傳遞多個序列(元組或列表),每兩個序列是一個X,Y向量對,在圖中構成一條折線。

                          如果要顯示的制定X軸的座標,可以像如下一樣:
                          plt.plot([1,2,3,4],[1,4,9,16])
                          形成點(1,1),(2,4),(3,9),(4,16)

                          控制線形(marker)和顏色

                          (1)線形,默認是實線solid-
                              ``'-'``             solid line style
                              ``'--'``            dashed line style
                              ``'-.'``            dash-dot line style
                              ``':'``             dotted line style
                              
                          (2)點的形狀:marker,默認爲point .
                              ``'.'``             point marker
                              ``','``             pixel marker
                              ``'o'``             circle marker
                              ``'v'``             triangle_down marker
                              ``'^'``             triangle_up marker
                              ``'<'``             triangle_left marker
                              ``'>'``             triangle_right marker
                              ``'1'``             tri_down marker
                              ``'2'``             tri_up marker
                              ``'3'``             tri_left marker
                              ``'4'``             tri_right marker
                              ``'s'``             square marker
                              ``'p'``             pentagon marker
                              ``'*'``             star marker
                              ``'h'``             hexagon1 marker
                              ``'H'``             hexagon2 marker
                              ``'+'``             plus marker
                              ``'x'``             x marker
                              ``'D'``             diamond marker
                              ``'d'``             thin_diamond marker
                              ``'|'``             vline marker
                              ``'_'``             hline marker
                              
                          (3)顏色對應如下,默認爲藍色b
                              'b'         blue
                              'g'         green
                              'r'         red
                              'c'         cyan
                              'm'         magenta
                              'y'         yellow
                              'k'         black
                              'w'         white
                          
                          

                          示例:
                          爲了區分同一個圖裏的多條曲線,可以爲每個X,Y向量對指定一個參數來標明該曲線的表現形式,默認的參數是’b-’,亦即藍色的直線,如果想用紅色的圓點來表示這條曲線,可以:

                          import matplotlib.pyplot as plt
                          plt.plot([1,2,3,4],[1,4,9,16],'ro')
                          

                            matplotlib不僅僅可以使用序列(列表和元組)作爲參數,還可以使用numpy數組。實際上,所有的序列都被內在的轉化爲numpy數組。同時plot函數還可以同時繪製多條線。

                            import numpy as np
                            import matplotlib.pyplot as plt
                            t=np.arange(0.,5.,0.2)
                            plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')#繪製三條線,t**2表示t的平方,即每個元素的都平方
                            plt.show()
                            

                              線條、marker、顏色可以無順序任意組合

                              import numpy as np
                              import matplotlib.pyplot as plt
                              t=np.arange(0.,5.,0.2)
                              plt.plot(t,t,'r--*',t,t**2,'s--b',t,t**3,':g')#繪製三條線,t**2表示t的平方,即每個元素的都平方
                              plt.axis([0,6,0,20])
                              #axis()函數接受形如[xmin,xmax,ymin,ymax]的參數,指定了X,Y軸座標的範圍。
                              plt.show()
                              

                                plt.scatter:散點圖

                                語法:plt.scatter(x, y, s, c ,marker, alpha,…)

                                • x,y: x軸與y軸的數據,都是向量,而且必須長度相等
                                • s: 點的面積。想讓所有點大小一樣就填一個數字,想不一樣就填一個向量
                                • c: 點的顏色。可填成RGB 三元數或顏色名稱或由 RGB 三元數組成的三列矩陣或顏色向量
                                選項 說明 對應的 RGB 三元數
                                ‘red’ 或 ‘r’ 紅色 [1 0 0]
                                ‘green’ 或 ‘g’ 綠色 [0 1 0]
                                ‘blue’ 或 ‘b’ 藍色 [0 0 1]
                                ‘yellow’ 或 ‘y’ 黃色 [1 1 0]
                                ‘magenta’ 或 ‘m’ 品紅色 [1 0 1]
                                ‘cyan’ 或 ‘c’ 青藍色 [0 1 1]
                                ‘white’ 或 ‘w’ 白色 [1 1 1]
                                ‘black’ 或 ‘k’ 黑色 [0 0 0]
                                #不同顏色的點
                                cValue = ['r','y','g','b','r','y','g','b','r']
                                plt.scatter(x,y,c=cValue)
                                
                                • 1
                                • 2
                                • 3
                                • marker: 點的形狀
                                • alpha: 透明度。[0,1]:1不透明,0透明
                                • edgecolors:輪廓顏色。和c類似,參數也相同
                                • linewidths:線寬。標記邊緣的寬度,默認是’face’

                                注意事項
                                color、marker等不能同時作爲一個參數,plt.scatter(x1, y1, ‘bo’, s=5)不合法。

                                示例1:

                                from numpy import *  
                                import matplotlib  
                                import matplotlib.pyplot as plt  
                                import numpy as np
                                x = random.rand(50,30)      #創建一個50行30列的多維數組(ndarray)
                                #basic  
                                f1 = plt.figure(1)          #創建顯示圖形輸出的窗口對象
                                plt.subplot(211)            #創建子座標系
                                #x[:,1]獲取第二列作爲一維數組,x[:,0]獲取第一列作爲一維數組
                                plt.scatter(x[:,1],x[:,0])  #畫散點圖
                                

                                with label

                                plt.subplot(212) #c重新創建座標系

                                #list(ones(20)) 創建1行20列的全爲1列表
                                #list(2ones(15)) 創建1行15列全爲2的列表
                                #list(3
                                ones(15) 創建1行15列全爲3的列表

                                label = list(ones(20))+list(2ones(15))+list(3ones(15)) #將列表合併到一起,共50列
                                label = array(label) #將列表轉爲數組

                                #15.0*label 將數組的每個值都乘以15.0
                                #x[:,1] 將x的第2列50行轉爲1行50列
                                #x[:,0] 將x的第1列50行轉爲1行50列

                                #x軸和y軸均50個點,兩個Label都是1行50列的數組
                                #從第一個點到第20個點的樣式相同,從第21到第35個點相同,從第36到第50個點相同
                                plt.scatter(x[:,1],x[:,0],15.0label,15.0label)

                                with legend

                                f2 = plt.figure(2) #創建顯示圖形輸出的窗口對象
                                idx_1 = np.where(label==1) #找label中爲1的位置

                                #畫圖 marker標識散點圖樣式 color標識顏色 label表示圖例的解釋 s表示散點的大小
                                p1 = plt.scatter(x[idx_1,1], x[idx_1,0], marker = ‘x’, color = ‘m’, label=‘1’, s = 30)
                                idx_2 = np.where(label==2) #找label中爲2的位置

                                p2 = plt.scatter(x[idx_2,1], x[idx_2,0], marker = ‘+’, color = ‘c’, label=‘2’, s = 50)
                                idx_3 = np.where(label==3) #找label中爲3的位置

                                p3 = plt.scatter(x[idx_3,1], x[idx_3,0], marker = ‘o’, color = ‘r’, label=‘3’, s = 15)
                                plt.legend(loc = ‘upper right’) #圖例的位置

                                plt.show()

                                  Python matplotlib(2D繪圖庫)2

                                  發表評論
                                  所有評論
                                  還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
                                  相關文章