matplotlib繪圖的基本語法爲:
pyplot.圖名(x, y, 參數=值),其中,x和y爲列表或Numpy數組。數組
import matplotlib.pyplot as plt import numpy as np import math %matplotlib inline ##讓繪圖顯示在Jupyter筆記本中 x01 = np.arange(0,9) ##創建Numpy數組 y01 = x01**2 x02 = np.linspace(-math.pi*2,math.pi*2,100) ##創建Numpy數組 y02 = np.sin(x02)*10 plt.figure(figsize=(6, 4)) ##設置圖表的大小,能夠省略,使用默認大小 plt.scatter(x01,y01,linewidth=1,label='linear') ##繪製散點圖,label爲圖例 plt.plot(x02,y02,label='scatter') ##繪製折線圖,這裏會與折線圖顯示在同一張圖表中 plt.title('Square numbers') ##設置圖表的標題 plt.xlabel('Value',fontsize=14) ##設置圖標x軸的標籤 plt.ylabel('Value of numbers',fontsize=14) ##設置圖標y軸的標籤 plt.axis([-math.pi*2,math.pi*2,-100,100]) ##設置座標軸的顯示區域 ##plt.xlim(-math.pi*2,math.pi*2) ##設置x軸的顯示區域 ##plt.ylim(-100,100) ##設置y軸的顯示區域 plt.legend() ##顯示圖例 plt.show() ##顯示繪圖 ##plt.savefig('f01.svg',format='svg') ##保存繪圖
subplots()函數的基本用法是f, ax = plt.subplots(ncols=列數, nrows=行數[, figsize=圖片大小, ...]),其中f爲所繪製的總圖表,ax爲所繪製的子圖標,能夠經過下標調用。svg
x = np.arange(0.01, 10, 0.01) y1 = 2*x - 6 y2 = np.log(x) y3 = np.exp(x) y4 = np.sin(x) f, ax = plt.subplots(ncols=2, nrows=2, figsize=(8, 6)) ax[0, 0].plot(x, y1) ax[0, 0].set_title("Linear") ax[0, 1].plot(x, y2) ax[0, 1].set_title("Log") ax[1, 0].plot(x, y3) ax[1, 0].set_title("Exp") ax[1, 1].plot(x, y4) ax[1, 1].set_title("Sin")
subplot()函數的基本用法爲:pyplot.subplot(nrows, ncols, index, 其餘參數),而後再使用plt.plot()函數繪圖。函數
x = np.arange(0.01, 10, 0.01) y1 = 2*x - 6 y2 = np.log(x) y3 = np.exp(x) y4 = np.sin(x) plt.figure(figsize=(8,6)) plt.subplot(221) ##也能夠寫做subplot(2,2,1) plt.plot(x, y1,label='Linear') plt.subplot(222) plt.plot(x, y2, label='Log') plt.subplot(223) plt.plot(x, y3, label='Exp') plt.subplot(224) plt.plot(x, y4, label='sin') plt.show()