2020年12月11日 星期五

畫出南投縣毛猪成交頭數-總數的曲線圖

 參考文章:

  1. 當Python遇見猪樂園,來看南投縣毛猪成交頭數-總數
  2. Matplotlib:好用的Python 2D繪圖套件

合併後的程式如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import requests
import json
r = requests.get('https://data.coa.gov.tw/Service/OpenData/FromM/AnimalTransData.aspx?$top=200&$skip=0')
text = json.loads(r.text)
X=[]
Y=[]
for d in text:
    if d['市場名稱'] == '南投縣':
        print(d['交易日期'],d['成交頭數-總數'])
        X.append(d['交易日期'])
        Y.append(d['成交頭數-總數'])

import matplotlib.pyplot as plt
plt.plot(X, Y)
plt.ylabel('number of pigs')
plt.show()

結果:


2020年12月5日 星期六

Matplotlib:好用的Python 2D繪圖套件

 參考網站:https://matplotlib.org/3.1.1/index.html

1.安裝指令

1
2
python -m pip install -U pip
python -m pip install -U matplotlib

2.範例集


3.畫線(1)
1
2
3
4
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

第二行的plot()函式中第一個參數是y軸的值。

執行結果:


使用語法:

plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

從以上語法來看,當plot()函式只有一個參數時,代表y軸,但有兩個參數時,第一個代表x軸。

4.畫線(2)
1
2
3
4
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.ylabel('some numbers')
plt.show()

第二行的plot()函式中第一個參數是x軸的值而第二個參數是y軸的值。

執行結果:


5.畫點(1)
1
2
3
4
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

說明:
plot()函式第三個參數是[fmt],[]代表可有可無,fmt的語法說明如下:

fmt = '[marker][line][color]'

共有三個參數marker, line, color,其格式如下:

標記(Markers)

字元說明
'.'點標記
','像素標記
'o'圓圈標記
'v'下三角標記
'^'上三角標記
'<'左三角標記
'>'右三角標記
'1'細下三角標記
'2'細上三角標記
'3'細左三角標記
'4'細右三角標記
's'方形標記
'p'五邊形標記
'*'星號標記
'h'六角1標記
'H'六角2標記
'+'加號標記
'x'乘號標記
'D'鑽石標記
'd'細讚豆標記
'|'垂直線標記
'_'水平線標記


線條樣式(Line Styles)

字元說明
'-'實線樣式
'--'虛線樣式
'-.'點劃線樣式
':'虛點樣式

顏色(Colors)

單個字母代碼代表的支持的顏色

字元顏色
'b'藍色
'g'線色
'r'紅色
'c'青色
'm'洋紅色
'y'黃色
'k'黑色
'w'白色

顏色參數如果是單獨存在,則可以另外使用任何matplotlib.colors規範,例如 全名(“綠色”)或十六進製字符串(“#008000”)。

執行結果:


6.畫點(2)

接下來說明一次畫出多條線,是使用plot()函式的第二種語法。

plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()




7.使用scatter函式畫圖

scatter的語法如下:

matplotlib.pyplot.scatter(xys=Nonec=Nonemarker=Nonecmap=Nonenorm=Nonevmin=Nonevmax=Nonealpha=Nonelinewidths=Noneverts=Noneedgecolors=None*plotnonfinite=Falsedata=None**kwargs)


本例僅使用到五個參數,說明如下:
x:表示x軸的數值。
y:表示y軸的數值。
c:表示顏色的數值,可有可無。
s:表示標量,可有可無,是指標記大小。
data:資料。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import matplotlib.pyplot as plt
import numpy as np

data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

執行結果:





8. 用分類變量畫圖

figure()函式的figsize參數是指寬度,高度(以英寸為單位)。
subplot()函式前三個參數分別是行列以及索引值,也可以用單一數字表示,例如131表示1行3列第1個。
subplot(nrows, ncols, index, **kwargs)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import matplotlib.pyplot as plt

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()




9.使用多個圖形和軸來畫圖


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()




10.在數據直方圖中加上文字

hist()函式第二個參數表示有筆資料。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

執行結果:


11.貼上文字

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import matplotlib.pyplot as plt
import numpy as np

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )

plt.ylim(-2, 2)
plt.show()

執行結果: