2017年4月28日 星期五

Python 畫圖工具整理

   在理解maching learning 時,發覺將data 可視化是非常重要的,整理目前python 畫圖工具及範例。

Matplotlib 畫圖工具

figure and subplot

所有的圖資訊都是在figure 物件中,figure 就像是畫布一樣,因此畫圖前必須先呼叫。subplot 是在figure 上定義有幾張圖表,如果沒有呼叫subplot,就是只有一張圖:

figure 範例:

from matplotlib import pylab as plt
plt.figure(figsize=(6,6))
plt.title('test')
plt.show()























第2行定義了figure 的大小 (寬6長6),第3行定義圖表名稱,第4行將圖show 出來。

subplot 範例:

from matplotlib import pylab as plt
plt.figure(figsize=(9,6))
plt.subplot(2,3,1)
plt.title('1')
plt.subplot(2,3,2)
plt.title('2')
plt.subplot(2,3,3)
plt.title('3')
plt.subplot(2,3,5)
plt.title('5')
plt.show()
















subplot 第1,2個參數定義figure x,y方向要切出幾個圖。範例為y方向切2塊,x方向切3塊 總共6塊小圖。第3個參數為指定那一個小圖,數字不能超過x*y,順序由左上往右下。

定義figure & subplot 後,就可以再圖上畫上資訊了

Plot 折線圖 or 散佈圖

from matplotlib import pylab as plt
plt.figure(figsize=(12,8))
plt.subplot(2,2,1)
plt.plot([0,1,2,3,4,5],[4,6,3,1,9,6],'ko-')
plt.subplot(2,2,2)
plt.plot([0,1,2,3,4,5],[4,6,3,1,9,6],'ro--')
plt.subplot(2,2,3)
plt.plot([0,1,2,3,4,5],[4,6,3,1,9,6],'bo')
plt.show()


















plot function 第1,2 參數是x軸數據及y軸數據。第3個參數是資料點的"顏色" , "標記樣式" , "線條樣式"。例如 "ko-" k代表黑色、圓標記點 、實心直線 ,"bo" 為藍色圓點無線。

hist 長條圖

from matplotlib import pylab as plt
import numpy as np
plt.figure()
plt.hist(np.random.randn(1000),range = (-2,2),bins=10,alpha=0.5)
plt.show()


















hist 第1個參數是輸入資料(一維格式)。畫出來的圖 x軸數據大小,y軸該大小出現的次數。
range 為x軸顯示範圍。bins 圖上要分成幾根長條圖,數字愈大分越細。alpha 為透明程度,數字愈小愈透明。


Scatter 散佈圖




from matplotlib import pylab
import numpy as np
import random

batch = np.ndarray(shape=(10,2), dtype=np.int32)
for i in range(10):
    batch[i,0]= random.randint(0, 20)
    batch[i,1]= random.randint(0, 20)
string = "1 2 3 4 5 6 7 8 9 10"
name = string.split()

pylab.figure(figsize=(10,5)) #figsize=(width,height) by inch
for i, label in enumerate(name):
    x,y=batch[i,:]
    pylab.scatter(x,y) #plot scatter point
    pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',ha='right', va='bottom') #label on each point
pylab.show()


pylab.figure(figsize=(10,5)) : 決定圖的大小
pylab.scatter(x,y) : 將點以x,y座標畫在圖上
pylab.annotate : 將文字映在圖上
       label :為映的文字
       xy :文字的座標
       xytext : 文字對xy座標的平移量,數字愈大移的愈遠
       va : 有'center'   'left'   'right'  三種選擇,意思是選擇用文字方塊的 中間/左邊/右邊對齊xy座標點
       ha: 有 'center'   'top'   'bottom' 'baseline,意思也是用文字方塊的上/中/下緣對齊座標,
             baseline 目前不知用處為何