# 基本介紹 首先最重要的是 import 這個模組,如果沒有的話要記得去下載 ```python import matplotlib.pyplot as plt ``` `figure` 是我們畫圖的基底,或者說底板,你可以在這個底板上面畫很多圖。 ```python fig = plt.figure(figsize=(19.2,10.8),facecolor="#DAFFBF",dpi=300) ``` `axe` 就是我們要畫的圖,也就是說你可以在 `figure` 上畫很多圖。 ```python ax_1 = fig.add_subplot(3,3,1) ``` 下面的程式碼畫了 5 張圖;而一個 figure 能畫幾張圖是由 `add_subplot(X,Y,index)` 當中的三個參數所決定的,其中 X 跟 Y 會把一張 figure 劃分出 X rows 跟 Y cols,而 index 代表是從左上角數來第幾張圖,從 1 開始 ```python= # generate one figure 1920x1080 fig = plt.figure(figsize=(19.2,10.8),facecolor="#DAFFBF",dpi=300) # generate axe(s) ax_1 = fig.add_subplot(3,3,1) # ax_2 = fig.add_subplot(3,3,2) ax_3 = fig.add_subplot(3,3,3) # ax_4 = fig.add_subplot(3,3,4) ax_5 = fig.add_subplot(3,3,5) # ax_6 = fig.add_subplot(3,3,6) ax_7 = fig.add_subplot(3,3,7) # ax_8 = fig.add_subplot(3,3,8) ax_9 = fig.add_subplot(3,3,9) plt.show() ``` 效果如下: ![](https://drive.google.com/uc?id=1rKI9IZ56hkg_PnZ8hXEx0JW5rc5CkVhm&export=download) 除此之外還可以將多個位置均畫同一張圖。 ```python # generate one figure fig = plt.figure(figsize=(19.2,10.8),facecolor="#DAFFBF",dpi=300) # generate axe(s) ax_1 = fig.add_subplot(3,3,(1,4)) ax_2 = fig.add_subplot(3,3,(2,3)) ax_5 = fig.add_subplot(3,3,5) ax_6 = fig.add_subplot(3,3,(6,9)) ax_7 = fig.add_subplot(3,3,(7,8)) plt.show() ``` 可以有下面酷炫的效果: ![](https://drive.google.com/uc?id=1jfS5ShOh5L7x_uqfPIqnjbj2fYK97TPJ&export=download) 但是要注意畫不出 L 型。 ## 各種部件 下面是各種會出現在一張圖裡面的部件。 ```python= # generate one figure fig = plt.figure() # generate axe(s) ax = fig.add_subplot(1,1,1) ax.scatter([1,2,3],[4,5,6],label='this is first legend') # inline legend ax.plot([10,20,30],label='this is second legend') # inline legend ax.set_title("This is title") ax.set_xlabel("this is x label") ax.set_ylabel("this is y label") ax.set_xticks(range(0,11,2)) ax.set_yticks(range(5,30,5)) ax.set_xlim(left = 0,right = 8) ax.set_ylim(bottom = 5, top = 15) ax.legend(loc = 'upper left',fontsize=14) # ax.legend(['this is first legend','this is second legend']) legend via method fig.savefig('basic3.png') plt.show() ``` ![](https://drive.google.com/uc?id=1_OJtwMwcMy49w1FsG_4_yrfl0BKgFxdN&export=download) - 每個部件都可以設置 `fontsize` 參數,通常 14 ~ 28 是個不錯的選擇範圍 - 這很重要,不然字太小或太大都不好看 - `legend` 有兩種設置方式,一個是在畫出資料的時候帶入 `label` 參數 - 要記得最後一定要加上 `ax.legend()`,裡面可以不用帶入任何東西 - 或者也可以像上面帶入位置參數,upper/lower/center + left/right - 沒有加上的話就不會有 label 出來 - 另一種是在 `legend()` 裡面依序帶入參數 ## 另一種畫法 其實也不一定要建立出 axe,我們可以直接用 plt 來畫出圖 ```python= plt.figure(figsize=(6.8,3.4)) plt.scatter([1,2,3],[4,5,6],label='this is first legend') # inline legend plt.plot([10,20,30],label='this is second legend') # inline legend plt.title("This is title") plt.xlabel("this is x label") plt.ylabel("this is y label") plt.xticks(range(0,11,2)) plt.yticks(range(5,30,5)) plt.xlim(left = 0,right = 8) plt.ylim(bottom = 5, top = 15) plt.legend(loc = 'upper center') # ax.legend(['this is first legend','this is second legend']) legend via method plt.savefig('basic4.png') plt.show() ``` ![](https://drive.google.com/uc?id=1qySvBOqxMfsB6IBit7EsZBcOQ-oIpDLW&export=download) 可以注意到所有的函數都只差在有沒有 `set_` 這個前綴,其他都是一樣的 --- # 散佈圖 Scatter 顧名思義,就是散佈的圖形,可以將資料以點的方式呈現。常用的參數就是 x 軸、y 軸、點大小,這三個。 ```python= import numpy as np plt.figure(figsize=(6.8,3.4)) x = np.linspace(0,100,50) y = np.log(1+x) plt.scatter(x=x,y=y,s=5) plt.savefig('scatter.png') plt.show() ``` ![](https://drive.google.com/uc?id=1IFUWt9nMm68yOy7DwUb9YqAW82Kx2_56&export=download) 另外還有一個東西是 Colormap。 # 長條圖 Bar 用來呈現離散的資料。`left` 代表 bar 的位置,預設是「中心」的位置 `height` 則是 bar 的高度。 每個 bar 的 x 軸可以想成是從 0 ~ 某個數的刻度,然後 bar 的中心會位在這些刻度上面。所以如果要畫多筆資料不讓他們重疊,那麼就需要對 left 做一些位移,如下面的範例。要注意位移的時候要考慮 bar 的寬度。 ```python stu = ['Student 1','Student 2','Student 3'] DSA = [4.3, 3.1, 3.7] ADA = [4.3, 2.8, 4.0] SP = [4.3, 3.4, 4.0] base = np.arange(len(team)) # [0,1,2] DSA_x = base + 0.2 * -1 ADA_x = base + 0.2 * 0 SP_x = base + 0.2 * 1 plt.figure(figsize=(6.8,3.4)) plt.bar(left = DSA_x,height = DSA, width = 0.2, label = 'DSA',color="blue") plt.bar(left = ADA_x,height = ADA, width = 0.2, label = 'ADA',color="green") plt.bar(left = SP_x,height = SP, width = 0.2, label = 'SP',color="orange") plt.xticks(x_axis,stu) plt.legend(fontsize=14,loc="upper right") plt.savefig("bar.png") plt.show() ``` ![](https://drive.google.com/uc?id=1GPLzYM6iT19wK19JIYR3h8ewSDkP67sD&export=download) 不過如果只有一筆資料的畫,不一定要像上面,先帶入 x 軸的刻度位置,然後再使用 xticks 給予 tag。我們也可以直接將 left 帶入 tag 的陣列。 # 直方圖 Histogram 用來呈現連續的資料。常見用法大致就是下面的三種圖,數量圖、機率密度函數 PDF,累積密度函數 CDF。 要注意的是 `bins` 參數跟 PDF 和 CDF 之間的關係。 `density` 這個參數的目的是讓圖形的面積加起來等於 1,也就是說每個 bar 的機率要乘上 bar 的寬度才會是「該區間的機率」,可以在下面的例子自己算算看,bar 的寬度是 5。而 CDF 則沒有這個問題,顯示的已經是乘好的結果。 ```python= np.random.seed(48763) fig = plt.figure(figsize=(10.8,19.2)) ax_origin = fig.add_subplot(3,1,1) ax_PDF = fig.add_subplot(3,1,2) ax_CDF = fig.add_subplot(3,1,3) normal = np.random.normal(loc = 50,scale = 20 ,size=20) bins = range(0,105,5) # bar width is 5 # origin hist ax_origin.hist(x = normal,alpha = 0.7,bins = bins) ax_origin.set_title("Origin") ax_origin.set_xticks(bins) ax_origin.grid(True) # PDF ax_PDF.hist(x = normal,alpha = 0.7,bins = bins,density = True) ax_PDF.set_title("PDF") ax_PDF.set_xticks(bins) ax_PDF.grid(True) # CDF ax_CDF.hist(x = normal,alpha = 0.7,bins = bins,density = True,cumulative=True) ax_CDF.set_title("CDF") ax_CDF.set_xticks(bins) ax_CDF.set_yticks(np.arange(0,1.05,0.05)) ax_CDF.grid(True) plt.savefig('histogram.png') plt.show() ``` ![](https://drive.google.com/uc?id=1enVy3XiMflNyC-4eGrFNe46SaytyXhmY&export=download) # 盒狀圖/箱形圖 box plot 好用的盒狀圖,幫助複習國小(還是國中?)所教過的圖表知識。圈圈是離群值。[請參閱維基](https://zh.wikipedia.org/zh-tw/%E7%AE%B1%E5%BD%A2%E5%9C%96) ```python= np.random.seed(48763) plt.figure() normal_1 = np.random.normal(loc = 50,scale = 2 ,size=500) normal_2 = np.random.normal(loc = 40,scale = 2 ,size=500) plt.boxplot((normal_1,normal_2),vert=False,labels=['first data','second data'],widths=0.5,capwidths=0.8) plt.savefig('box.png') plt.show() ``` ![](https://drive.google.com/uc?id=1mpMGg0Tn2W2ebk0JcGXuBigMtbJRi1j-&export=download) second 的字被截掉了....。