# NUMPY / Matplotlib 學習筆記
> [name=wa.__.wa]
職訓所課堂學習筆記,還有很多未提到的語法用法,只介紹常用的
導讀官方API文件,英文搜尋對應關鍵字,找 cheat sheet。
臨時放置區:
```
- `concatenate`:例如將兩個維度相同的數組在現有維度上組合,維度不變,如 [1, 2] 和 [3, 4] 組合成 [1, 2, 3, 4]。
- `stack`:例如將數組沿著新軸堆疊,增加一個新維度,如 [1, 2] 和 [3, 4] 堆疊成 [[1, 2], [3, 4]],新維度為 2x2。
NYCU Data Science Software 2024
陽交大資料科學軟體實作 2024 授課內容:
https://youtube.com/playlist?list=PLl6jkZVaP8zq9rw3lZ5DCg0joGldrhgmo&si=4sTCeLBxzPcGCFh4
https://pool-sunshine-1a4.notion.site/Data-Science-Software-and-Computation-Experiments-2024-4753fbae4e5c4bc08e8c112a79e9f1b6
```
> [TOC]
<!--
[Python 課堂講義筆記](https://absorbing-bookcase-ffc.notion.site/2024-07-31-79b30c36611940e9bec9ab1f23d957fa) -->
## 學習資源
老師提供方法:從官方文件 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 不可修改
串列跟元組只有 `一維` 概念
```python=
list1 = [1,2,3,4,5]
tuple1 = (1,2,3,4,5)
print(dir(tuple1))
# __虛線__ 忽略 只剩下 count,index
print(tuple1.count(1))
# "1" 出現幾次 (conunt)
print(tuple1.index(0))
# 索引值 index 來取得元素
```
```python=
# 串列建構式
list1 = []
print(type(list1))
list2 = list()
print(type(list2))
# <class 'list'>
# <class 'list'>
```
## ndarray array object
### numpy 陣列範例
官方文件提供範例:
[ndarray: ](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html)
```python=
import numpy as np
# ndarray ( numpy 陣列) 表示方式
np.ndarray(shape=(2,2), dtype=float, order='F')
```
ndim 維度 (rank)
shape 幾列幾行 外型
dtype 資料型態
order 資料讀取順序
F = Row-major
C = Column-major

圖片引用來源:https://en.wikipedia.org/wiki/Row-_and_column-major_order
使用 ndarray 物件
判別重點:
1. 維度 dimension
2. 幾列幾行 shape
3. 資料型態 dtype
```python=
import numpy as np
nd1 = np.ndarray(shape=(5,), dtype=float, order='F')
nd2 = np.ndarray(shape=(1,5))
nd3 = np.ndarray(shape=(5,1))
nd4 = np.ndarray(shape=(1,5))
print(nd1.ndim, nd2.ndim, nd3.ndim, nd4.ndim)
print(nd1.shape, nd2.shape, nd3.shape, nd4.shape)
print(nd1.dtype, nd2.dtype, nd3.dtype, nd4.dtype)
# 1 2 2 2
# (5,) (1, 5) (5, 1) (1, 5)
# float64 float64 float64 float64
# 5, 一維陣列
# 5,1 前列後行,5列1行
# 1,5 前列後行,1列5行
# (自創記法:前列腺(先))
```
## 串列取值索引
```python=
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
# 使用 matplotlib 顯示圖片
plt.figure(figsize=(8,8))
plt.imshow(s, cmap='gray')
# 'gray' 表示灰階模式
plt.show()
# 使用方法:https://matplotlib.org/3.5.3/api/_as_gen/matplotlib.pyplot.show.html
```
取如下圖紅色區域的資料:

```pyhton=
s1 = s[1:-1]
s2 = []
for i in s1:
s2.append(i[1:-1])
print(s2)
```
上述寫法可以換成串列生成式 語法糖寫法
> s2 = \[ item\[1:-1\] for item in s2 \]
* 備註:不學其他模組,一樣可以取資料,不過會很麻煩
使用 numpy 模組好處:
1.元素型態一致
2.更有效率切片
## Numpy 增加/刪除資料
[numpy insert](https://numpy.org/doc/stable/reference/generated/numpy.insert.html) 有需要再看,很少用
### np.append
#### 一維陣列
nd.append(nd物件,元素)
```
import numpy as np
nd001 = np.array([10,20,30,40,50])
nd001 = np.append(nd001, 60)
nd001
```
#### 二維陣列
np.append(nd物件,二維物件,指定行或列)

[參考資料:Numpy中ndim、shape、dtype、astype的用法_numpy ndim-CSDN博客](https://blog.csdn.net/Da_wan/article/details/80518725)
*備註:行跟列用法不同
### np.delete
#### 一維陣列
修改資料:利用索引修改
np.delete(nd物件,[指定索引位置])
```
import numpy as np
# 建立一個一維陣列
x = np.array([10, 20, 30, 40, 50, 60])
# 刪除索引為 0 和 4 的元素
x = np.delete(x, [0, 4])
print(x) # 輸出結果應該是 [20, 30, 40, 60]
```
#### 二維陣列
只能一次刪除一整行或列
nd.delete(nd物件,索引,指定行或列)
axis=0 看列(y軸)的索引
axis=1 看行(x軸)的索引
```python=
# 建立一個二維陣列
y = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 刪除第一行(行索引為 0)
y = np.delete(y, 0, axis=0)
print("Delete first row:")
print(y) # 輸出應該是 [[4, 5, 6], [7, 8, 9]]
# 刪除第三列(列索引為 2)
y = np.delete(y, 2, axis=1)
print("Delete third column:")
print(y) # 輸出應該是 [[4, 5], [7, 8]]
```
### ndarray 切片索引方式
[列範圍,行範圍]
舉例:ax[0:1,1:2]
## numpy Routines and objects by topic
[Array creation routines](https://numpy.org/doc/stable/reference/routines.html)
產生陣列的函式,直接調用
>list1 = [10,20,30]
nd = np.array(list1)
會回傳一個物件:ndarray
## Matplotlib pyplot
[Matplotlib.pyplot 官方文件語法說明](https://matplotlib.org/3.5.3/api/_as_gen/matplotlib.pyplot.html)
必填參數:像是陣列的物件,或是,PIL Image (pillow 模組)
cmap :填色盤,可選[顏色](https://matplotlib.org/stable/users/explain/colors/colormaps.html)

### 繪圖座標設定 figure/axes
[figure 物件 ](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html)= 圖紙
[axes 物件](https://steam.oxxostudio.tw/category/python/example/matplotlib-figure-axes.html) = 座標系統 圖案
[subplots](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html) 建立多個圖表
**fig_kw
All additional keyword arguments are passed to the [pyplot.figure](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure) call.
回傳 Returns:
fig : Figure
ax : Axes or array of Axes
`fig_kw`:所有額外的關鍵字參數都會傳遞給 `pyplot.figure` 函式。包括設定圖表的尺寸、背景色等屬性。
---


`**kwargs`:這些關鍵字參數將被傳遞給 Figure 建構函式,進一步設定圖表。
```python=
fig, ax = plt.subplots(nrows=1,ncols=3,figsize=(16,8),facecolor="AliceBlue",layout="constrained")
fig.suptitle("figure")
ax[0,0].set_title('first axis', loc="center", fontweight="bold")
ax[0,1].set_title('second axis', loc="center", fontweight="bold")
ax[0,0].imshow(s, cmap="gray", aspect='equal', extent=[0, len(s[0]), 0, len(s)])
ax[0,1].imshow(s2, cmap="gray", aspect='equal', extent=[0, len(s[0]), 0, len(s)])
plt.show()
```
** Matplotlib 兩張圖片縮放、座標維持相同方式:**
`aspect` 參數用於控制圖像在軸上的縮放方式
equal : 每個 pixels 設定為正方形
`extent` 參數設定圖像在座標中的位置和大小
範圍:(左、右、下、上)
設定圖像在座標中的邊界。
`extent` (left, right, bottom, top)
- **left** 和 **right** 指定圖像 x 軸的起點和終點。
- **bottom** 和 **top** 指定圖像 y 軸的起點和終點。
```python
plt.imshow(image_data, extent=(0, 3, 0, 2))
# x 軸從 0 延伸到 3
# y 軸從 0 延伸到 2
```
[Matplotlib `imshow` 官方文件語法說明](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html)。


**其他設定**
參考資料:
https://python-graph-gallery.com/2-horizontal-barplot/
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html#matplotlib.axes.Axes.bar
資料圖形視覺化
```python=
import pandas as pd
import numpy as np
# 資料讀取&清洗篩選
df = pd.read_csv('hsinchu-location.csv')
df = df.drop(columns=['Countycode','YYYMM'],axis=1)
# drop 丟棄
df = df.astype('int32')
df['民國年月'] = df['民國年月'].astype('str')
df = df.set_index('民國年月')
df2 = df.loc['10801',:]
# print(df)
print(df.info())
import matplotlib.pyplot as plt
# 設定中文字體
plt.rcParams['font.family'] = 'Heiti TC'
# plt.figure(figsize=(10, 6)) # 調整圖形尺寸,寬度為10,高度為6
import random
available_colors = ['red', 'green', 'blue', 'yellow', 'purple']
# colors = []
# for i in range(len(df.columns)):
# chosen_color = random.choice(available_colors)
# colors.append(chosen_color)
colors = random.choices(available_colors,k=len(df.columns))
fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(10,8),constrained_layout=True)
fig.suptitle('這是我要打的標題')
ax.bar(df.columns, df2, width=0.5, align='center',color=colors)
# ax.legend(title='圖例')
# 位置,label
ax.set_xticks([n for n in range(df.columns.shape[0])],df.columns,color='green',rotation=20,fontsize='12')
ax.set_yticks([50000,100000,150000,200000],['50,000','10,0000','15,0000','20,0000'], color='green',rotation=20,fontsize='12')
ax.set_xlabel('地點', fontweight='bold', fontsize='22')
ax.set_ylabel('人數', fontweight='bold', fontsize='22')
print(df.columns.shape[0])
# ax.set_xticklabels(df.columns)
# 位置,標籤
# plt.bar(df.columns, df2, color=colors) # 使用隨機選擇的顏色
# plt.barh(y=df.columns, width=df2,color=colors)
# plt.xlabel('遊憩地點')
# plt.ylabel('人數')
# plt.title('人數統計ss')
# plt.xticks(rotation=45) # 旋轉 x 軸標籤以避免重疊
# plt.show()
```

## numpy 一維陣列切片與索引
一維陣列處理
```python=
list1 = [1,2,3,4,5]
tuple1 = (1.1,2.2,3.4,4.4,5.5)
nd1 = np.array(list1)
a = nd1[2]
nd2 = np.array(tuple1)
b = nd2[2]
print(type(nd1))
print(type(nd2))
print(type(a))
print(type(b))
```
```pyhton=
<class 'numpy.int64'>
<class 'numpy.float64'>
```
### Scalars 純量 標量
int 記得這幾個就可

### 資料型態一致性:字串
```python=
list2 = [1,2,"sudo",4,5]
tuple2 = (1.1,2.2,"sudo",4.4,5.5)
nd3 = np.array(list2)
nd3
array(['1', '2', 'sudo', '4', '5'], dtype='<U21')
```
### numpy 資料形式轉換
astype 資料轉型
```python=
# 程式引用來源:https://steam.oxxostudio.tw/category/python/numpy/numpy-dtype.html#a2
a = np.array([1, 2, 3, 4], dtype="int32")
b = a.astype('float32')
print(a) # 1, 2, 3, 4
print(b) # 1., 2., 3., 4,
```
## numpy 二維陣列切片與索引
將資料轉 array
<!-- ~~前列腺先~~ -->

array[列範圍,行範圍]
```
a = nd4[0:3,0]
print(a)
# output
# [10 20 40]
```
## numpy 二維陣列轉置(Transpose)
numpy : `ndarray.T`
使用串列生成式的方式:
```python=
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
transposed_matrix = []
for i in range(4): # 因為每個子列表有 4 個元素
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
print(f"Adding column {i}: {transposed_row}")
transposed_matrix.append(transposed_row)
print("Transposed matrix:")
print(transposed_matrix)
# Adding column 0: [1]
# Adding column 0: [1, 5]
# Adding column 0: [1, 5, 9]
# Adding column 1: [2]
# Adding column 1: [2, 6]
# Adding column 1: [2, 6, 10]
# Adding column 2: [3]
# Adding column 2: [3, 7]
# Adding column 2: [3, 7, 11]
# Adding column 3: [4]
# Adding column 3: [4, 8]
# Adding column 3: [4, 8, 12]
# Transposed matrix:
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
# [ n for xxx for xx ] 此為雙迴圈與巢狀串列不同
```
## 巢狀雙迴圈
一維結構


## 巢狀串列生成式
二維結構
```python=
# [[row[i] for row in 串列 ] for i in range(每列有幾行)]
st = [[ row[i] for row in s ]for i in range(len(s[0]))]
# 或是使用 zip() BIF內建函式
# print(list(zip(*s)))
# zip 垂直分割 打包成元組
# *s 元組解包
```

參考資料:
https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions
# numpy 產生有規則的二維數列
[ [ 行 ] 列 ]
原本:
```python=
a = [ [ row*4 for col in range(5) ] for row in range(4) ]
```
可以使用 numpy 內建的函式
## 產生陣列 Array creation routine
```
# numpy.arrange 等距
a = np.arange(6)
print(f"arange : {a}")
# arange : [0 1 2 3 4 5]
# np.linspace 等分
b = np.linspace(0, 10, 4)
print(f"linspace : {b}")
# linspace : [ 0. 2.5 5. 7.5 10. ]
# 創建一個形狀為 (5, 2) 數值為 1 陣列
c = np.ones((5, 2))
print(f"ones : {c}")
# ones :
[[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]]
# 創建一個形狀為 (5, 2) 數值為 0 陣列
d = np.zeros((5, 2))
print(f"zeros : {d}")
# zeros :
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
# 通過列表創建一個 2x3 陣列
e = np.array([[1, 2, 3], [4, 5, 6]])
print(f"array : {e}")
# array :
[[1 2 3]
[4 5 6]]
```
## 操作陣列
numpy.reshape
numpy.repeat
numpy.tile
numpy.ravel
numpy.tile
```pyhton=
# 將 a 重新塑形為 (2, 3) 形狀
f = np.reshape(a, (2, 3))
print(f"reshape (2,3) : {f}")
# reshape (2,3) :
[[0 1 2]
[3 4 5]]
# 使用 -1 自動計算所需列數,保持每列 3 個元素
# 1d --> 2d
f_1 = np.reshape(a, (-1, 3))
print(f"reshape (-1,3) : {f_1}")
# 一樣
# 將 f_1 陣列展平
# 2d --> 1d
f = np.ravel(f_1)
print(f"ravel ( reshape 過的 a ) : {f}")
# ravel ( reshape 過的 a ) : [0 1 2 3 4 5]
# 通過列表創建一個 2x3 陣列
e = np.array([[1, 2, 3], [4, 5, 6]])
print(f"array : {e}")
# 將 e 陣列展平
g = np.ravel(e)
print(f"ravel e : {g}")
# 將 a 陣列重複 3 列 2 行
h = np.tile(a, (3, 2))
print(f"tile a (3,2) :")
print(h)
#tile a (3,2) :
[[0 1 2 3 4 5 0 1 2 3 4 5]
[0 1 2 3 4 5 0 1 2 3 4 5]
[0 1 2 3 4 5 0 1 2 3 4 5]]
z = np.array([[1, 2, 3], [4, 5, 6]])
# 將 z 陣列中的每個元素重複 3 次
# axis 決定要往哪個方向,default 0 x軸方向
i = np.repeat(z, 3, axis=1)
print(f"repeat z : ")
print(i)
repeat z :
[[1 1 1 2 2 2 3 3 3]
[4 4 4 5 5 5 6 6 6]]
j = np.repeat(z, 3, axis=0)
repeat j :
[[1 2 3]
[1 2 3]
[1 2 3]
[4 5 6]
[4 5 6]
[4 5 6]]
```
範例:[0,4,8,12,16] 產生特殊陣列
```
import numpy as np
# 原始陣列
arr = np.array([0, 4, 8, 12, 16])
# arr = np.arange(20, 0, -4)
print("原始陣列:")
print(arr)
# 使用 tile 生成四列一行
tiled_arr = np.tile(arr, (4, 1))
print("使用 tile 生成四列一行的結果:")
print(tiled_arr)
# 第一種方式:先 repeat 再 reshape
# 將每個元素重複四次
repeat_arr = np.repeat(arr, 4, axis=0)
print("repeat 後的陣列:")
print(repeat_arr)
# 重新塑形為 (-1, 4),自動計算所需行數,每行四個元素
repeat_arr_reshape = np.reshape(repeat_arr, (-1, 4))
print("reshape 後的陣列:")
print(repeat_arr_reshape)
# 第二種方式:先 reshape 再 repeat
# 將陣列 reshape 為 (5, 1),即五列一行
arr_reshaped = np.reshape(arr, (5, 1))
# 對每行進行橫向重複四次
arr_repeated = np.repeat(arr_reshaped, 4, axis=1)
print("第二種方式的結果:")
print(arr_repeated)
```
練習:
```python=
a = np.array([[1, 2, 3]])
b = np.tile(a, 2)
c = np.repeat(a, 2, axis=0)
c = np.tile(c,3)
print(b)
print(c)
```
# Numpy nd.T 應用
```python=
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)) #順時針旋轉90度
nd5 = np.rot90(nd1, k=1, axes=(0,1)) #逆時針旋轉90度
# 或是用 zip
# print(list(zip(*s)))
# *s 元組解包
# 創建一個圖形和三個子圖
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
### 產生黑白漸層
```python=
import matplotlib.pyplot as plt
import numpy as np
# 設定字體為 macOS 內建的中文字體
plt.rcParams['font.family'] = 'Heiti TC'
list1 = [ [ 255//64*row for col in range(256) ] for row in range(64) ] * 4
nd1 = np.array(list1)
nd2= np.rot90(nd1, k=2, axes=(1,0))
nd3 = np.hstack((nd1, nd2))
nd4 = np.rot90(nd1, k=1, axes=(1,0))
nd5 = np.rot90(nd4, k=2, axes=(1,0))
nd6 = np.hstack((nd4, nd5))
nd7 = np.vstack((nd3,nd6))
nd8 = nd7.astype("uint16")
# 創建一個圖形和三個子圖,子圖共享 x 軸和 y 軸
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20,7), facecolor="AliceBlue",constrained_layout=True)
fig.suptitle("numpy 漸層", fontsize=20, fontweight="bold")
# 設定標題和圖像顯示
ax.set_title('nd 應用', loc="center", fontweight="bold")
ax.imshow(nd7, cmap="Grays", vmin=0, vmax=255)
plt.axis('off') # 同時隱藏 x 軸 y 軸 的刻度和標籤
# 隱藏座標用法:
# https://cloud.baidu.com/article/2797113
```
### 產生彩色漸層
#### 先產生單一顏色
總共八格顏色
2列4行
2列4行
2列4行
最後疊加起來
| 紅色 | 綠 | 藍 | 黃 |
| --- | -------- | -------- | -------- |
| 洋紅 |青 | 黑 | 白 |
顏色,以及 ndarray 的表示方式
> 看不懂 QQ

```python=
import matplotlib.pyplot as plt
import numpy as np
nd1 = np.ndarray(shape=(2,4,3), dtype="uint8")
# red
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
# green
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
#blue
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
# 設定字體為 macOS 內建的中文字體
plt.rcParams['font.family'] = 'Heiti TC' # 或者 'PingFang 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') # 同時隱藏 x 軸 y 軸 的刻度和標籤
print(nd1)
```
單一漸層:
```python=
list_color = [ [ 255//64*row for col in range(256) ] for row in range(64) ]
```
進階漸層合併:
(實作過程發現偶爾顏色會有錯誤...不知道為什麼QQ 可能 Mac 處理顏色快取問題?)

```python=
import matplotlib.pyplot as plt
import numpy as np
# nd1 = np.ndarray(shape=(2,4,3), dtype="uint8")
# 第一排
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)
# print(list_array.shape)
# red
nd1[:,:,0] = list_color
# green
nd1[:,:,1] = 0
# blue
nd1[:,:,2] = 0
nd2 = np.vstack((nd1,nd1,nd1,nd1))
# red
nd3[:,:,0] = 0
# green
nd3[:,:,1] = list_color
# blue
nd3[:,:,2] = 0
# nd4綠色
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")
# [[ 256-col*4 for col in range(64) ] for row in range(256) ]
# 這個邏輯是基於寬的轉成窄的
# 藍色
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(nd7)
print(nd8.shape)
print(nd8.dtype)
# try:
# nd8 = np.hstack((nd5, nd7))
# print("nd8 shape:", nd8.shape)
# print("nd8 dtype:", nd8.dtype)
# except ValueError as e:
# print("Error:", e)
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))
# 設定字體為 macOS 內建的中文字體
plt.rcParams['font.family'] = 'Heiti TC' # 或者 'PingFang 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') # 同时隐藏x轴和y轴的刻度线和标签
plt.show()
# 如果已合併其他陣列,例如 nd7
plt.imshow(nd7,vmin=0, vmax=255) # 確保 nd7 的尺寸和色彩數據正確
plt.title('Combined Gradient in nd7')
plt.axis('off')
plt.show()
```
**補充**
```python=
import numpy as np
import matplotlib.pyplot as plt
nd1 = np.ndarray(shape=(2,4,3), dtype="uint8")
nd1[:,:,0] = [[255, 0, 0, 255], [255, 0, 255, 0]]
nd1[:,:,1] = [[0, 255, 0, 255], [0, 255, 255, 0]]
nd1[:,:,2] = [[0, 0, 255, 0], [255, 255, 255, 0]]
plt.imshow(nd1)
plt.title('Custom Color Grid')
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 來判讀到底是哪個軸向