NUMPY / Matplotlib 學習筆記
wa.__.wa
職訓所課堂學習筆記,還有很多未提到的語法用法,只介紹常用的
導讀官方API文件,英文搜尋對應關鍵字,找 cheat sheet。
臨時放置區:
學習資源
老師提供方法:從官方文件 API Reference 看語法
Numpy 官方網站
https://numpy.org/doc/stable/reference/index.html
從官方網站 API Module 開始看起
NumPy 函式庫
https://steam.oxxostudio.tw/category/python/numpy/about-numpy.html
2021 iThome 鐵人賽【Day 24】NumPy (1)
https://ithelp.ithome.com.tw/articles/10279537
Numpy simple learning
https://simplelearn.tw/numpy-intro/
Numpy 常用語法整理
https://dysonma.github.io/2020/10/29/Numpy常用語法整理/
老師推薦的書 / cheat sheet:
Numpy reshape cheatsheet
https://towardsdatascience.com/reshaping-numpy-arrays-in-python-a-step-by-step-pictorial-tutorial-aed5f471cf0b
Python資料分析 Pandas
https://www.eslite.com/product/10012011762682452090006
Matplotlib cheatsheet
https://matplotlib.org/cheatsheets/
其中最重要的這張圖:

自己找到台大資料科學社團的文章提供的圖也不錯
https://medium.com/ntu-data-analytics-club/python-advanced-ii-資料視覺化-matplotlib-pandas-seaborn-b479f460acf2
串列 與 元組 差異
Mutable vs Immutable
list 可以修改
tuple 不可修改
串列跟元組只有 一維
概念
ndarray array object
numpy 陣列範例
官方文件提供範例:
ndarray:
ndim 維度 (rank)
shape 幾列幾行 外型
dtype 資料型態
order 資料讀取順序
F = Row-major
C = Column-major

圖片引用來源:https://en.wikipedia.org/wiki/Row-_and_column-major_order
使用 ndarray 物件
判別重點:
- 維度 dimension
- 幾列幾行 shape
- 資料型態 dtype
串列取值索引
s = [
[157,153,174,168,150,152,129,151,172,161,156,156],
[155,182,163, 74, 76, 62, 33, 17,110,210,180,154],
[180,180, 50, 14, 34, 6, 10, 33, 48,106,150,181],
[206,109, 5,124,131,111,120,204,166, 15, 56,180],
[194, 64,137,251,237,239,210,220,227, 87, 71,201],
[172,106,207,233,233,214,220,239,228, 98, 74,206],
[198, 84,179,209,116,215,211,158,119, 75, 10,169],
[199, 97,166, 84, 10,168,134, 11, 31, 62, 22,148],
[199,168,191,193,158,227,178,143,182,106, 36,190],
[206,174,156,252,216,231,140,178,228, 43, 96,234],
[190,216,116,149,236,187, 86,150, 79, 38,218,241],
[190,224,147,100,227,210,127,102, 36,101,255,224],
[190,214,173, 66,103,143, 96, 50, 2,109,249,215],
[187,196,236, 75, 1, 81, 47,000, 6,217,255,211],
[183,202,237,145, 0, 0, 12,108,200,138,243,236],
[196,206,123,207,177,121,123,200,176, 13, 96,218]
]
print(len(s))
print(type(s))
print(s[0])
print(s[0][0])
import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.imshow(s, cmap='gray')
plt.show()
取如下圖紅色區域的資料:

上述寫法可以換成串列生成式 語法糖寫法
s2 = [ item[1:-1] for item in s2 ]
使用 numpy 模組好處:
1.元素型態一致
2.更有效率切片
Numpy 增加/刪除資料
numpy insert 有需要再看,很少用
np.append
一維陣列
nd.append(nd物件,元素)
二維陣列
np.append(nd物件,二維物件,指定行或列)

參考資料:Numpy中ndim、shape、dtype、astype的用法_numpy ndim-CSDN博客
*備註:行跟列用法不同
np.delete
一維陣列
修改資料:利用索引修改
np.delete(nd物件,[指定索引位置])
二維陣列
只能一次刪除一整行或列
nd.delete(nd物件,索引,指定行或列)
axis=0 看列(y軸)的索引
axis=1 看行(x軸)的索引
ndarray 切片索引方式
[列範圍,行範圍]
舉例:ax[0:1,1:2]
numpy Routines and objects by topic
Array creation routines
產生陣列的函式,直接調用
list1 = [10,20,30]
nd = np.array(list1)
會回傳一個物件:ndarray
Matplotlib pyplot
Matplotlib.pyplot 官方文件語法說明
必填參數:像是陣列的物件,或是,PIL Image (pillow 模組)
cmap :填色盤,可選顏色

figure 物件 = 圖紙
axes 物件 = 座標系統 圖案
subplots 建立多個圖表
**fig_kw
All additional keyword arguments are passed to the pyplot.figure call.
回傳 Returns:
fig : Figure
ax : Axes or array of Axes
fig_kw
:所有額外的關鍵字參數都會傳遞給 pyplot.figure
函式。包括設定圖表的尺寸、背景色等屬性。


**kwargs
:這些關鍵字參數將被傳遞給 Figure 建構函式,進一步設定圖表。
** Matplotlib 兩張圖片縮放、座標維持相同方式:**
aspect
參數用於控制圖像在軸上的縮放方式
equal : 每個 pixels 設定為正方形
extent
參數設定圖像在座標中的位置和大小
範圍:(左、右、下、上)
設定圖像在座標中的邊界。
extent
(left, right, bottom, top)
- left 和 right 指定圖像 x 軸的起點和終點。
- bottom 和 top 指定圖像 y 軸的起點和終點。
Matplotlib imshow
官方文件語法說明。


其他設定
參考資料:
https://python-graph-gallery.com/2-horizontal-barplot/
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html#matplotlib.axes.Axes.bar
資料圖形視覺化

numpy 一維陣列切片與索引
一維陣列處理
Scalars 純量 標量
int 記得這幾個就可

資料型態一致性:字串
numpy 資料形式轉換
astype 資料轉型
numpy 二維陣列切片與索引
將資料轉 array

array[列範圍,行範圍]
numpy 二維陣列轉置(Transpose)
numpy : ndarray.T
使用串列生成式的方式:
巢狀雙迴圈
一維結構


巢狀串列生成式
二維結構

參考資料:
https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions
numpy 產生有規則的二維數列
[ [ 行 ] 列 ]
原本:
可以使用 numpy 內建的函式
產生陣列 Array creation routine
操作陣列
numpy.reshape
numpy.repeat
numpy.tile
numpy.ravel
numpy.tile
範例:[0,4,8,12,16] 產生特殊陣列
練習:
Numpy nd.T 應用
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as img
image = img.imread('face_low_pixel.jpg')
plt.rcParams['font.family'] = 'Heiti TC'
s = [
[157,153,174,168,150,152,129,151,172,161,156,156],
[155,182,163, 74, 76, 62, 33, 17,110,210,180,154],
[180,180, 50, 14, 34, 6, 10, 33, 48,106,150,181],
[206,109, 5,124,131,111,120,204,166, 15, 56,180],
[194, 64,137,251,237,239,210,220,227, 87, 71,201],
[172,106,207,233,233,214,220,239,228, 98, 74,206],
[198, 84,179,209,116,215,211,158,119, 75, 10,169],
[199, 97,166, 84, 10,168,134, 11, 31, 62, 22,148],
[199,168,191,193,158,227,178,143,182,106, 36,190],
[206,174,156,252,216,231,140,178,228, 43, 96,234],
[190,216,116,149,236,187, 86,150, 79, 38,218,241],
[190,224,147,100,227,210,127,102, 36,101,255,224],
[190,214,173, 66,103,143, 96, 50, 2,109,249,215],
[187,196,236, 75, 1, 81, 47,000, 6,217,255,211],
[183,202,237,145, 0, 0, 12,108,200,138,243,236],
[196,206,123,207,177,121,123,200,176, 13, 96,218] ]
s1 = s[1:-1]
s2 = [row[1:-1] for row in s1]
st = [[ row[i] for row in s ]for i in range(len(s[0]))]
nd1 = np.array(image)
nd2 = nd1.T[::-1,:]
nd3 = nd1.T[:,::-1]
nd4 = np.rot90(nd1, k=1, axes=(1,0))
nd5 = np.rot90(nd1, k=1, axes=(0,1))
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20,7), facecolor="AliceBlue",constrained_layout=True)
fig.suptitle("numpy array", fontsize=20, fontweight="bold")
ax[0].set_title('first axis', loc="center", fontweight="bold")
ax[1].set_title('second axis', loc="center", fontweight="bold")
ax[2].set_title('third axis', loc="center", fontweight="bold")
ax[0].imshow(image, cmap="Grays", vmin=0, vmax=255)
ax[1].imshow(nd4, cmap="Grays", vmin=0, vmax=255)
ax[2].imshow(nd5, cmap="Grays", vmin=0, vmax=255)
產生 ndarray 並操作
hstack,vstack 往右合併,往下合併
rot90 轉90度
難,需消化理解:
list1 = [ [ 255//64*row for col in range(256) ] for row in range(64) ] * 4
產生黑白漸層
產生彩色漸層
先產生單一顏色
總共八格顏色
2列4行
2列4行
2列4行
最後疊加起來
顏色,以及 ndarray 的表示方式
看不懂 QQ

import matplotlib.pyplot as plt
import numpy as np
nd1 = np.ndarray(shape=(2,4,3), dtype="uint8")
nd1[0,0,0] = 255
nd1[0,1,0] = 0
nd1[0,2,0] = 0
nd1[0,3,0] = 255
nd1[1,0,0] = 255
nd1[1,1,0] = 0
nd1[1,2,0] = 255
nd1[1,3,0] = 0
nd1[0,0,1] = 0
nd1[0,1,1] = 255
nd1[0,2,1] = 0
nd1[0,3,1] = 255
nd1[1,0,1] = 0
nd1[1,1,1] = 255
nd1[1,2,1] = 255
nd1[1,3,1] = 0
nd1[0,0,2] = 0
nd1[0,1,2] = 0
nd1[0,2,2] = 255
nd1[0,3,2] = 0
nd1[1,0,2] = 255
nd1[1,1,2] = 255
nd1[1,2,2] = 255
nd1[1,3,2] = 0
plt.rcParams['font.family'] = 'Heiti TC'
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20,7),constrained_layout=True)
fig.suptitle("numpy 漸層", fontsize=20, fontweight="bold")
ax.set_title('nd 應用', loc="center", fontweight="bold")
ax.imshow(nd1, vmin=0, vmax=255)
plt.axis('off')
print(nd1)
單一漸層:
進階漸層合併:
(實作過程發現偶爾顏色會有錯誤…不知道為什麼QQ 可能 Mac 處理顏色快取問題?)

import matplotlib.pyplot as plt
import numpy as np
nd1 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd3 = np.ndarray(shape=(64,256,3), dtype="uint8")
list_color = [ [ 255//64*row for col in range(256) ] for row in range(64) ]
list_array = np.array(list_color)
nd1[:,:,0] = list_color
nd1[:,:,1] = 0
nd1[:,:,2] = 0
nd2 = np.vstack((nd1,nd1,nd1,nd1))
nd3[:,:,0] = 0
nd3[:,:,1] = list_color
nd3[:,:,2] = 0
nd4 = np.vstack((nd3,nd3,nd3,nd3))
nd4 = np.rot90(nd4, k=2, axes=(1,0))
nd5 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd6 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd7 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd5[:,:,0] = 0
nd5[:,:,1] = 0
nd5[:,:,2] = list_color
nd5 = np.rot90(nd5, k=1, axes=(1,0))
nd5 = np.hstack((nd5,nd5,nd5,nd5))
nd6[:,:,0] = list_color
nd6[:,:,1] = list_color
nd6[:,:,2] = 0
print(nd5.shape)
print(nd5.dtype)
nd7 = np.vstack((nd6,nd6,nd6,nd6))
print(nd7.shape)
print(nd7.dtype)
nd8 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd8 = np.hstack((nd5,nd7))
print(nd8.shape)
print(nd8.dtype)
print("nd8 shape:", nd8.shape)
print("nd8 dtype:", nd8.dtype)
nd9 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd9 = np.hstack((nd4,nd2))
nd10 = np.ndarray(shape=(64,256,3), dtype="uint8")
nd10 = np.vstack((nd9,nd8))
plt.rcParams['font.family'] = 'Heiti TC'
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12,8), facecolor="AliceBlue",constrained_layout=True)
fig.suptitle("numpy 漸層", fontsize=20, fontweight="bold")
ax.set_title('nd 應用', loc="center", fontweight="bold")
ax.imshow(nd10,vmin=0, vmax=255)
plt.title('ALL Gradient')
plt.axis('off')
plt.show()
plt.imshow(nd7,vmin=0, vmax=255)
plt.title('Combined Gradient in nd7')
plt.axis('off')
plt.show()
補充
tensoflow, keras 使用大量廣播計算
numpy 運算概念:自動廣播 Broadcast
matplotlib cmap 可使用的顏色
ValueError: '' is not a valid value for cmap; supported values are 'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Grays', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_grey', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gist_yerg', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'grey', 'hot', 'hot_r', 'hsv', 'hsv_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'seismic', 'seismic_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'turbo', 'turbo_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'winter', 'winter_r'
蠻多特殊用法的…
尤其三維蠻難想像跟理解…x,y,z
網路教學都各自畫圖表述(軸向會不太一樣)。
2,3,3
行,列,顏色通道
先記著未來如果想學:
用一個 1~25 連續陣列取 max 來判讀到底是哪個軸向