# Matplotlib
---
## 凡事先import
```python
import matplotlib.pyplot as plt
```
----
## 畫一張空的圖
```python
plt.plot()
plt.show()
```
----
## 加上標題及格線
```python
plt.title("uniform accelerated motion") #標題
plt.xlabel("Time") #x軸標題
plt.ylabel("Velocity") #y軸標題
plt.grid(True) #格線
plt.plot()
plt.show()
```
----
## 調整刻度
```python
plt.xticks([0,1,2,3,4])
plt.yticks([0,0.8,1.0,1.3,1.7])
plt.show()
```
----
* plt.axis([xmin, xmax, ymin, ymax])
```python
plt.axis([0,4,0,2])
plt.show()
```
---
## 折線圖
----
### Case 1: 只給y值
x會自動被設成 0, 1, ..., N
```python
plt.plot([0, 1, 4, 9, 16])
plt.show()
```
----
### Case 2: 給x值和y值
```python
x = [0, 0.2, 0.4, 0.6, 0.8]
y = [ i**2 for i in x ]
plt.plot(x, y)
plt.show()
```
----
### 修改樣式
```python
x = [0, 0.2, 0.4, 0.6, 0.8]
y = [ i**2 for i in x ]
plt.plot(x, y, 'r:', linewidth=5)
plt.show()
```
`r`代表紅色(red),`:`代表虛線
----
用 `plt.plot?` 看看有哪些樣式和顏色

---
## 直方圖 (bar chart)
----
### 直的
```python
langs = ('Python', 'C', 'Haskell', 'Rust')
idxs = range(len(langs))
popularity = [9,4,8,7]
plt.bar(idxs, popularity, align='center')
plt.xticks(idxs, langs)
plt.ylabel('Popularity')
plt.title('Programming languages')
plt.show()
```
----
### 橫的
```python
langs = ('Python', 'C', 'Haskell', 'Rust')
idxs = range(len(langs))
popularity = [9,4,8,7]
plt.barh(idxs, popularity, align='center')
plt.yticks(idxs, langs)
plt.xlabel('Popularity')
plt.title('Programming languages')
plt.show()
```
----
### 兩張圖疊一起
```python
bar_width = 0.25
langs = ('Python', 'C', 'Haskell', 'Rust')
popularity_tw = [9,4,8,7]
popularity_us = [10,5,1,3]
idxs_tw = range(len(langs))
idxs_us = [ x+bar_width for x in idxs_tw ]
idxs_label = [ x+bar_width/2 for x in idxs_tw ]
plt.bar(idxs_tw, popularity_tw, bar_width, align='center', color='g', label='TW')
plt.bar(idxs_us, popularity_us, bar_width, align='center', color='m', label='US')
plt.xticks(idxs_label, langs)
plt.ylabel('Popularity')
plt.title('Programming languages')
plt.legend() #顯示label
plt.show()
````
---
## 圓餅圖 (pie chart)
----
```python
status = ('AC', 'WA', 'RE', 'TLE', 'CE')
count = [11, 4, 9, 3, 5]
plt.pie(count, labels=status, autopct='%1.1f%%',
startangle=30)
plt.axis('equal') #讓x軸 y軸等比例
plt.show()
```
----
分離某塊
```python
status = ('AC', 'WA', 'RE', 'TLE', 'CE')
explode = (0.1, 0, 0, 0, 0)
count = [11, 4, 9, 3, 5]
plt.pie(count, explode=explode, labels=status,
autopct='%1.1f%%', startangle=30)
plt.axis('equal') #讓x軸 y軸等比例
plt.show()
```
---
## 動畫
----
```python
import matplotlib.animation as animation
animation.FuncAnimation(fig, func, frames=frames,
init_func=init_func, interval=interval)
```
* func: 每次更新畫面之函數
* frames: iterable (像list的東西)
* init_func: 初始函數
* interval: 每隔多少ms更新一次畫面
----
### 流程圖

----
### 範例
```python
import matplotlib.animation as animation
import math
def update(i):
line.set_ydata([ math.sin(v + i*math.pi/10) for v in x ])
return [line]
def init():
return [line]
x = []
v = 0
while v < math.pi * 6:
x.append(v)
v += 0.01
y = [ math.sin(v) for v in x ]
fig, ax = plt.subplots()
[line] = ax.plot(x, y)
ax.axis([min(x), max(x), -3, 3])
ani = animation.FuncAnimation(fig, update, frames=range(0,200), interval=25, repeat=True, init_func=init)
plt.show()
```
----
* 動畫無法直接在jupyter notebook裡面看,請使用terminal
* 或轉成HTML5影片
```python
from IPython.display import HTML
HTML(ani.to_html5_video())
```
---
## 參考資料
[matplotlib官網](https://matplotlib.org/)docs及examples
---
## 上課練習
### NEOJ統計
----
### 說明
給你一個neoj的題號,計算該題每種結果(AC,WA etc.)的人數有多少,並畫成圓餅圖
----
### API
傳入一個題號,此函數會回傳該題在NEOJ上的submission的list
```python
import requests
def get_neoj_status(probid):
ret = []
count = 1
while len(ret) < count:
params = {'offset': len(ret), 'filter': {'problem_uid': probid}}
r = requests.post('https://neoj.sprout.tw/api/challenge/list', json=params)
result = r.json()
ret.extend(result['data'])
count = result['count']
return ret
```
----
其中每一個submission長得如下:
```
{'metadata': {'memory': 30692, 'result': 3, 'runtime': 120},
'problem': {'checker': 'diff',
'lang': 'python3',
'memlimit': 65536,
'name': '修羅道的開始',
'revision': '351559ab22d93f9a01945b4a49f5befce015624f',
'subtask': [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
'timelimit': 1000,
'uid': 100},
'state': 2,
'submitter': {'category': 0, 'name': 'Administrator', 'uid': 1},
'timestamp': '2017-02-22T02:32:29.784723+00:00',
'uid': 1}
```
`['metadata']['result']`就是該submission的結果
----
結果對照表:
1. Accepted
2. Wrong Answer
3. Runtime Error
4. Time Limit Exceed
5. Memory Limit Exceed
6. Compile Error
7. Other