<style>
.reveal {
font-size: 30px;
}
.reveal h1 {
font-size: 42px;
}
</style>
# NCKU ES Python 視覺化 - Matplotlib
###### tags:`NCKU_ES` `python lecture`
---
# Matplotlib Introduction
資料視覺化對於了解資料的本質相當重要
:::info
本篇中的 function 大家千萬不要背起來,只要知道有這種語法,需要用的時候再去找就好了!
Tip: 請練習 google 的技巧
:::
----
## 基本畫圖流程
1. import matplotlib
2. (Optional)畫圖前的初始化或是設定,E.X. 要畫在哪一張圖上...
3. 用 `plot()` 、`scatter()` 、`arrow()` 等等函數畫圖
4. 用 `show()` 或 `pause()` 等等函數顯示畫好的圖
----
## Matplotlib [Cheat Sheet](https://python-graph-gallery.com/cheat-sheets/)

---
## import
在使用 matplotlib 時,如果只有一張圖片,我們通常用 pyplot 這個 module 來做全域繪圖
```python=
import matplotlib.pyplot as plt
```
>`matplotlib.pyplot` is a state-based interface to matplotlib. It provides a MATLAB-like way of plotting.
---
## Plot
原型:
```python=
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
```
基本用法
```python=
plot(x, y) # plot x and y using default line style and color
plot(x, y, 'bo') # plot x and y using blue circle markers
plot(y) # plot y using x as index array 0..N-1
plot(y, 'r+') # ditto, but with red plusses
```
----
## Plot
比較 fancy 的用法
```python=
plot(x, y, 'go--', linewidth=2, markersize=12)
plot(x, y, color='green', marker='o', linestyle='dashed',
linewidth=2, markersize=12)
plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
```
- 如果重複呼叫 `plot()` 會畫在同一張 figure (圖)上
- 在畫的時候記得標 label 之後就可以自動產生 legend (圖例)
----
## Plot
你各位應該可以發現, matplotlib 承襲了 matlab 繪圖標號的語法:
`bo` 表示顏色為 `blue` 並且用 circle (o) 作為畫圖的 marker。
更詳細資料請自己 [參考](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.plot.html)
----
## Document
Reading the [document](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.plot.html)
#### 不要排斥英文
#### 遇到不知道的用法 google 是你最佳的幫手
- 如何 google 到正確的資訊?
- 不用記住每一個語法,但要有概念
- 習慣用英文找資料
----
## 更多不同 marker
看這邊 [marker](https://matplotlib.org/3.1.1/api/markers_api.html)
:::info
你可以指定 marker="..."
去指定你想要的 marker
:::
----
## 更多不同 color
List of named colors 看這邊 [color](https://matplotlib.org/3.1.0/gallery/color/named_colors.html)
:::info
你可以指定 color="..."
去指定你想要的 color
:::
----
## 練習
畫出以下函數圖形
\begin{equation}
y=2.714^{-0.1t}cos(t), t \in [0, 50]
\end{equation}
:::success
1. 可以利用 numpy.linspace() 產生一連串均勻分布的數字 [參考](https://hackmd.io/CvLfWp-cQky2cnMjI6pWGA#linspace)
2. numpy 有許多 [數學函數](https://numpy.org/doc/stable/reference/routines.math.html) 可以使用,例如 numpy.power()、numpy.cos()...
3. 用 plt.show() 可以畫出圖表
:::
----
## 參考結果

---
## Scatter()
散佈圖
----
## 語法
```python=
matplotlib.pyplot.scatter(x, y, s=None, c=None,
marker=None, cmap=None, norm=None, vmin=None,
vmax=None, alpha=None, linewidths=None, verts=None,
edgecolors=None, *, plotnonfinite=False, data=None,
**kwargs)[source]
```
----
## 練習
嘗試把下列函數畫出來,t 範圍取 0~10 ,並取 1000 個 sample
\begin{equation}
y=cos(i*t), where\ i \in [1, 3]
\end{equation}
:::info
### 繪出圖例
可以在 scatter 時,加入 `label` 這個屬性,並且利用
```python
matplotlib.pyplot.legend()
```
### [For loop 用法](https://hackmd.io/@yencheng/Byuy66RPw#For-Loop)
:::
----
## 範例結果

----
## Example
```python=
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 10, 1000)
for i in range(1, 4):
y = np.cos(i*t)
plt.scatter(t, y, label="y"+str(i))
plt.legend()
plt.show()
```
---
# 其他有趣的繪圖 function
- 柱狀圖 [bar](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.bar.html)
- 繪製箭頭 [arrow](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.arrow.html)
- 繪製任意多邊形 [fill](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.fill.html)
- 資料視覺化 [colorbar](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.colorbar.html#matplotlib.pyplot.colorbar)
- 三維資料視覺化 [contour](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.contour.html#matplotlib.pyplot.contour)
- 寫字 [text](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.text.html#matplotlib.pyplot.text)
----
## 設定 limits
- 設定 x 方向邊界範圍 [`xlim()`](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.xlim.html#matplotlib.pyplot.xlim)
```python=
left, right = xlim() # return the current xlim
xlim((left, right)) # set the xlim to left, right
xlim(left, right) # set the xlim to left, right
```
- 設定 y 方向邊界範圍 [`ylim()`](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.ylim.html#matplotlib.pyplot.ylim)
----
## 設定 title
[title](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.title.html#matplotlib.pyplot.title)
```python=
matplotlib.pyplot.title(label, fontdict=None,
loc=None, pad=None, *, y=None, **kwargs)
```
**通常在畫完圖後,要執行 `show()` 之前,將圖片的各種屬性設定好**
----
## 設定 label
[xlabel](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.xlabel.html#matplotlib.pyplot.xlabel)
[ylabel](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.ylabel.html#matplotlib.pyplot.ylabel)
## 設定 Grid
[grid](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.grid.html#matplotlib.pyplot.grid)
---
# 練習
模擬一個球體在 bounding box 中的運動,設計適當的邊界條件,讓物體不會超過邊界
You can start from the following code
```python=
import matplotlib.pyplot as plt
# Environment
left_wall = -10
right_wall = 10
ground = 0
g = -9.8
# Pingpong initial state
initial_height = 10
def main():
pos = [0, initial_height-1]
vel = [1, -0.1]
# Create random velocity of each points
for time in range(100):
# Clear screen
plt.cla()
"""
Add your code here
"""
plt.pause(0.1)
if __name__ == "__main__":
main()
```
{"metaMigratedAt":"2023-06-15T15:16:41.611Z","metaMigratedFrom":"YAML","title":"NCKU ES Python 部課 - Matplotlib","breaks":true,"slideOptions":"{\"theme\":\"League\",\"transition\":\"fade\",\"spotlight\":{\"enabled\":false},\"slideNumber\":true,\"parallaxBackgroundImage\":\"https://wallpaperboat.com/wp-content/uploads/2019/10/programming-02.jpg\"}","contributors":"[{\"id\":\"af67681e-fb2e-4298-8e92-448b36d346a6\",\"add\":5967,\"del\":51}]"}