python擴充庫2—matplotlib,pythonmatplotlib
1 載入matplotli的繪圖模組,並重新命名為plt
import matplotlib.pyplot as plt
2 折線圖
import matplotlib.pyplot as pltimport numpy as npx = np.arange(9)y = np.sin(x)z = np.cos(x)# marker資料點樣式,linewidth線寬,linestyle線型樣式,color顏色plt.plot(x, y, marker="*", linewidth=3, linestyle="--", color="orange")plt.plot(x, z)plt.title("y and z")plt.xlabel("x")plt.ylabel('height')# 設定圖例plt.legend(["y","z"], loc="upper right")plt.grid(True)plt.show()
3 散佈圖
x = np.random.rand(10)y = np.random.rand(10)plt.scatter(x,y)plt.show()
4 柱狀圖
x = np.arange(20)y = np.random.randint(0,30,20)plt.bar(x, y)plt.show()
5 餅圖
x = np.random.randint(1,10,4)plt.pie(x)plt.show()
6 長條圖
mean, sigma = 0, 1x = mean + sigma*np.random.randn(1000) #randn為產生常態分佈plt.hist(x,50)plt.show()
7 子圖
subplot(numRows, numCols, plotNum) #行,列,地區號
# figsize繪圖對象的寬度和高度,單位為英寸,dpi繪圖對象的解析度,即每英寸多少個像素,預設值為80plt.figure(figsize=(8,6),dpi=100)# subplot(numRows, numCols, plotNum)# 一個Figure對象可以包含多個子圖Axes,subplot將整個繪圖區域等分為numRows行*numCols列個子領域,按照從左至右,從上到下的順序對每個子領域進行編號# subplot在plotNum指定的地區中建立一個子圖AxesA = plt.subplot(2,2,1)plt.plot([0,1],[0,1], color="red")plt.subplot(2,2,2)plt.title("B")plt.plot([0,1],[0,1], color="green")plt.subplot(2,1,2)plt.title("C")plt.plot(np.arange(10), np.random.rand(10), color="orange")# 選擇子圖Aplt.sca(A)plt.title("A")plt.show()
8 在圖中顯示中文
matplotlib預設無法顯示中文,可直接在程式修改字型
from matplotlib.font_manager import FontPropertiesimport matplotlib.pyplot as pltimport numpy as npfont = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) t = np.linspace(0, 10, 1000)y = np.sin(t)plt.plot(t, y)plt.xlabel(u"時間", fontproperties=font) plt.ylabel(u"振幅", fontproperties=font)plt.title(u"正弦波", fontproperties=font)plt.show()