Matplotlib 可以建立多數類型的圖表,如條形圖,散點圖,條形圖,餅圖,堆疊圖,3D 圖和地圖圖表。首先,爲了實際使用 Matplotlib,咱們須要安裝它。若是你安裝了更高版本的 Python,你應該可以打開 cmd.exe 或終端,而後執行:pip install matplotlib。或者在安裝Anaconda的狀況下能夠在環境中查找matplotlib並Apply。函數
爲了可以在程序中使用matplotlib,咱們須要在程序的開頭將其引入:import matplotlib,一般咱們使用較多的是pyplot這個模塊,所以import matplotlib.pyplot as plt,接下來就能夠在程序中使用他們了。spa
練習1:繪製三角函數圖像,併爲圖像增長圖例,添加圖表標題,x軸、y軸標題。rest
代碼:code
x1=np.arange(0,2,0.01) y1=np.sin(2*np.pi*x1) x2 = np.arange(0,2,0.01) y2 =np.cos(2*np.pi*x2) #在同一副圖裏畫出兩個函數的圖像 plt.plot(x1,y1,label="sin(x)") plt.plot(x2,y2,label="cos(x)") plt.legend() plt.show()
程序運行結果:blog
練習2:繪製條形圖ip
代碼:cmd
x1=[1,3,5,7,9] y1=[1,2,5,4,8] x2=[2,4,6,8,10] y2=[3,2,4,7,1] plt.bar(x1,y1,label="ex.1") plt.bar(x2,y2,label="ex.2") plt.legend() plt.xlabel("bar number") plt.ylabel("bar height") plt.title("Hoho") plt.show()
結果:it
Pyplot.bar()函數能夠繪製條形圖,並指定條形圖的圖例,顏色等參數。一樣地,能夠給圖標的座標軸設置標題以及爲圖標設置標題。pip
練習3:繪製直方圖io
代碼:
population_ages =[22,55,62,45,21,22,34,42,42,4,99,102,110,120, 1,21,122,130,111,115,112,80,75,65,54,44,43,42,48] bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130] plt.hist(population_ages, bins, histtype='bar', rwidth=0.8,label="ex.01") plt.xlabel("x") plt.ylabel("y") plt.legend() plt.title("Interesting Graph") plt.show()
程序結果:
Pyplot.hist()函數能夠繪製直方圖,用以描述頻數的分佈情況。在這個函數中,能夠指定要畫的數據所存儲的變量,直方圖類型(histtype),寬度,圖例等參數。
練習4:繪製散點圖
代碼:
x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2] plt.scatter(x,y) plt.show()
程序結果:
在這段代碼中,咱們只須要指定每一個點的X值和Y值,而後使用pyplot.scatter()函數便可繪製,很是簡單。
練習5:繪製堆疊圖
堆疊圖用於顯示『部分對總體』隨時間的關係。 堆疊圖基本上相似於餅圖,只是隨時間而變化。
代碼:
days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13] plt.plot([],[],color='m', label='Sleeping', linewidth=8) plt.plot([],[],color='c', label='Eating', linewidth=8) plt.plot([],[],color='r', label='Working', linewidth=8) plt.plot([],[],color='k', label='Playing', linewidth=8) plt.legend() plt.stackplot(days,sleeping,eating,working,playing,colors=["r","g","b","m"]) plt.show()
程序結果:
練習6:繪製餅圖
餅圖很像堆疊圖,只是它們位於某個時間點。 一般,餅圖用於顯示部分對於總體的狀況,一般以%爲單位。 幸運的是,Matplotlib 會處理切片大小以及一切事情,咱們只須要提供數值。
代碼:
slices = [7,2,2,13] activities = ['sleeping','eating','working','playing'] cols = ['c','m','r','b']#指定每一部分繪製時的顏色 plt.pie(slices, labels=activities, colors=cols, startangle=90,#開始繪製的角度,設置爲90°是爲了便於觀看 shadow= True, explode=(0,0.1,0,0),#設置eating部分突出,對應於第二個下標 autopct='%1.1f%%')#將百分比放置在圖表上 plt.title('Graph t') plt.show()
程序結果: