2021/10/18 NLP Matplotlib(範例)

Simple plot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%matplotlib inline #此行目的是為了畫在jupyter notebook裡

#import 需要的套件
import numpy as np
import matplotlib.pyplot as plt

#在 -pi 和 pi 間,以等差數列的方式取256個點,endpoint=True(包含stop)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
#print(X)
C,S = np.cos(X), np.sin(X) #分別計算cos、sin值
plt.plot(X,C) #使用plt.plot()繪圖並帶入x,y座標
plt.plot(X,S)
plt.title('this is title') #設定圖表標題
plt.ylabel('y label') #設定y軸名稱
plt.xlabel('x label') #設定x軸名稱
plt.grid() #顯示網格

#plt.show() #匯出圖表
plt.savefig("./simple_plot.png",dpi=72) #將圖表存成檔案;dpi是解析度

要特別注意,plt.savefig()之前不能有plt.show(),不然存到的會是空白圖。

numpy.linspace(等差數列): 此陣列以等差數列的形式產生,指定個數


Figure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%matplotlib inline #此行目的是為了畫在jupyter notebook裡
#import必要套件
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

#在 -pi 和 pi 間,以等差數列的方式取256個點,endpoint=True(包含stop)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)#分別計算cos、sin值

#要畫一張新的圖只要重新呼叫 plt.figure() 即可
#以下分開繪製 cos、sin 的圖
plt.figure()
plt.plot(X,C) #使用plt.plot()繪圖並帶入x,y座標

#重新繪製另一張圖
plt.figure()
plt.plot(X,S, color='red', linewidth=10) #將線段設為紅色,linewidth=10 用來調整線段寬度

plt.show() #繪出兩個圖表



Subplot

畫子圖,將原來的一張圖分成數個子圖
subplot函數需要使用幾個參數(row,col,# of plot)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#%matplotlib inline #此行目的是為了畫在jupyter notebook裡
#import必要套件
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4)) #開始繪圖,指定 figsize
# plt.subplot(n_rows, n_cols, plot_num)
plt.subplot(2, 2, 1) #繪製子圖 plt.subplot(row,col,number of plot) 第一張圖
plt.plot([0, 1], [0, 1]) #繪製從(0,0)到(1,1)的點

plt.subplot(2,2,2) #第二張圖
plt.plot([1, 1], [0, 2]) #以此類推

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

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


#tight_layout automatically adjusts subplot params so that the subplot(s) fits in to the figure area.
plt.tight_layout() #用於自動調整子圖參數以提供指定的填充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
# plt.subplot(n_rows, n_cols, plot_num)
plt.subplot(2, 1, 1)
# figure splits into 2 rows, 1 col, plot to the 1st sub-fig
plt.plot([0, 1], [0, 1])

plt.subplot(2,3,4)
# figure splits into 2 rows, 3 col, plot to the 4th sub-fig
plt.plot([0, 1], [0, 2])

plt.subplot(2,3,5)
# figure splits into 2 rows, 3 col, plot to the 5th sub-fig
plt.plot([0, 1], [0, 3])

plt.subplot(2,3,6)
# figure splits into 2 rows, 3 col, plot to the 6th sub-fig
plt.plot([0, 1], [0, 4])
plt.tight_layout()

要注意這個例題的圖表順序,因為第一張圖表佔據3個位置(1~3),所以下面的圖表要以4、5、6來排列。

補充資料:

Matplotlib讓資料視覺化!
NumPy基礎介紹
subplot和subplots绘制子图
Python Matplotlib.pyplot.tight_layout()用法及代碼示例


分享到