# [Python] Matplotlib 資料視覺化
###### tags: `Python` `Matplotlib`
---
第一次使用須先安裝套件
`pip install matplotlib`
Import matplotlib
首先我們先 import:
`import matplotlib.pyplot as plt`

Create Data
建立一些資料
```
years = [2010,2011,2012,2013,2014,2015,2016,
2017,2018,2019,2020,2021,
2022,2023]
pops = [1262,1650,2525,2758,3018,3322,3682,
4061,4440,4853,5310,6520,
6930,7349]
```
使用plt.plot(),將years,pops資料內容放到函數內:
`plt.plot(years,pops)`
接著將圖表顯示出來:
`plt.show()`
完整程式碼

執行產生圖表
在終端機輸入指令執行py程式
`python3 mat.py`
結果圖

改變顏色
`plt.plot(years,pops,color=(255/255,100/255,100/255))`
結果圖

label
圖表完成後可以自訂標籤
```
plt.title("Test") # title
plt.ylabel("People") # y label
plt.xlabel("Year") # x label
```
結果圖

Multilines 增加第二條線
`quits = [1,1,1,2,2,2,2,3,3,3,3,3,4,5]`
上面第一條線的數值稍微調整一下
```
pops = [2,3.8,3,3.7,4,5.2,6,
6.7,7.5,8,9.2,9.8,
10,10.7]
```
統整一下
```
pops = [2,3.8,3,3.7,4,5.2,6,
6.7,7.5,8,9.2,9.8,
10,10.7]
quits = [1,1,1,2,2,2,2,3,3,3,3,3,4,5]
```
結果圖

也可以稍微改寫一下
```
lines = plt.plot(years,pops,years,quits)
# 設定第一條折線的顏色為藍色
lines[0].set_color('blue')
# 設定第二條折線的顏色為紅色
lines[1].set_color('r')
# 設定第一條折線的數據標記的形狀為圓形
lines[0].set_marker('o')
# 設定第二條折線的數據標記的形狀為三角形
lines[1].set_marker('^')
```
結果圖

顯示網格 plt.grid()
`plt.grid()`

plt.setp()
```
# 設定兩條線的數計標記形狀為圓形
plt.setp(lines,marker = "o")
```
結果圖

結合Numpy繪製
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1.0, 0.01)
y1 = np.sin(4*np.pi*x)
y2 = np.sin(2*np.pi*x)
lines = plt.plot(x, y1, x, y2)
plt.setp(lines, linestyle='--')
plt.show()
```
結果圖

# 繪製圓餅圖
```
import matplotlib.pyplot as plt
import numpy as np
labels='Apple','guava','watermelon','banana'
# 設定每塊的大小
size=[60,72,98,84]
# 設定分開的數值(距離)
separated = (.1,0,0,0)
# autopct='%1.1f%%'是用來顯示百分比
plt.pie(size,labels=labels,autopct='%1.1f%%',explode= separated)
# 圓餅圖比例相等
plt.axis('equal')
plt.show()
```
結果圖

結合pandas
```
import matplotlib.pyplot as plt
import pandas as pd
# 定義資料
data = {'names':['Apple','guava','watermelon','banana'],
'jan':[124,156,176,101],
'feb':[111,153,161,110],
'march':[92,86,33,55]}
# 將資料設定為DataFrame格式,放到變數df
df=pd.DataFrame(data,columns=['names','jan','feb','march'])
# 定義總大小
df['total']=df['jan']+df['feb']+df['march']
# 定義顏色
colors = [(1,.4,.4),(1,.6,1),(.5,.3,1),(.7,.7,.2),(.6,.2,.6)]
# 定義圓餅圖
plt.pie( df['total'] ,
labels = df['names'],
colors = colors,
autopct='%1.1f%%',
)
# 設定等比例
plt.axis('equal')
plt.show()
```
結果圖
