1. 程式人生 > 實用技巧 >26、matplotlib 介紹2: 常用的統計圖形

26、matplotlib 介紹2: 常用的統計圖形

常用的統計圖形

bar 函式

用於繪製柱狀圖

plt.bar(x,y)

● x:標示在x軸上的定性資料的類別。

● y:每種定性資料的類別的數量。

barh 函式

用於繪製條形圖

plt.barh(x,y)

● x:標示在y軸上的定型資料的類別。

● y:每種定性資料的類別的數量。

hist 函式

用於繪製直方圖

plt.hist(x)

pie 函式

用於繪製餅圖

plt.pie(x)

polar 函式

用於繪製極線圖

plt.polar(theta,r)

● theta:每個標記所在射線與極徑的夾角。

● r:每個標記到原點的距離。

scatter 函式

用於繪製氣泡圖

plt.scatter(x,y)

● x:x軸上的數值。

● y:y軸上的數值。

● s:散點標記的大小。

● c:散點標記的顏色。

● cmap:將浮點數對映成顏色的顏色對映表。

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

a = np.random.randn(100)
b = np.random.randn(100)
# colormap:RdYlBu
plt.scatter(a,b,
            s=np.power(10*a+20*b,2),
            c=np.random.rand(100),
            cmap=mpl.cm.RdYlBu,
            marker="o")
plt.show()

stem 函式

用於繪製棉棒圖

plt.stem(x,y)

● x:指定棉棒的x軸基線上的位置。

● y:繪製棉棒的長度。

● linefmt:棉棒的樣式。

● markerfmt:棉棒末端的樣式。

● basefmt:指定基線的樣式。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.5,2*np.pi,20)
y = np.random.randn(20)
plt.stem(x,y,linefmt="-.",markerfmt="o",basefmt="-")
plt.savefig("棉棒圖.png")
plt.show()

boxplot 函式

用於繪製箱線圖

plt.boxplot(x)

errorbar 函式

用於繪製誤差棒圖

plt.errorbar(x,y,yerr=a,xerr=b)

● x:資料點的水平位置。

● y:資料點的垂直位置。

● yerr:y軸方向的資料點的誤差。

● xerr:x軸方向的資料點的誤差。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.1,0.6,6)
y = np.exp(x)
plt.errorbar(x,y,fmt="bo:",yerr=0.2,xerr=0.02)
plt.xlim(0,0.7)
plt.savefig("誤差棒圖.png")
plt.show()