Python資料視覺化影象庫MatPlotLib基本影象操作

birdlove1987發表於2017-02-18

什麼是MatPlotLib?


    Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. 


簡單來說就是資料視覺化工具。


下面介紹一下MatPlotLib的基本圖形畫法:


1.散點圖:


import numpy as np
import matplotlib.pyplot as plt

height=[161,170,182,175,173,165]
weight=[50,58,80,70,69,55]

plt.scatter(height,weight,s=200)#散點圖繪製函式

plt.show()




2.折線圖:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x=np.linspace(-10,10,6)
y=x**2
plt.plot(x,y) #plot函式本身就是繪線函式
plt.show()



3.條線圖:


import numpy as np
import matplotlib.pyplot as plt

N=5

y=[20,10,30,25,15]

index = np.arange(N)

p1 = plt.bar(left=index, height=y,width=0.5,bottom=100,color='red') #繪製條形圖函式

plt.show()



4.直方圖:


import numpy as np
import matplotlib.pyplot as plt

mu = 100  # 均值
sigma = 20  # 方差
x = mu + sigma * np.random.randn(2000)

plt.hist(x, bins=100,color='red',normed=True)#繪製直方圖函式

plt.show()



5.餅狀圖


import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

labels = 'A', 'B', 'C', 'D'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0) #設定其中第二塊與主餅分開0.05

plt.axes(aspect=1) #使餅狀圖為正圓

plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) #繪製餅圖函式

plt.show()



6. 箱型圖


import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(size=(100, 4), loc=0.0, scale=1.5) #產生四組資料

labels = ['A','B','C','D']

plt.boxplot(data, labels=labels, sym='o') #箱型圖繪製函式

plt.show()


感覺比matlab的繪圖功能強大不少啊!(我對matlab知之甚少,大牛不要懟我啊!)




相關文章