一、簡單示例
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 x = np.arange(3,8,1) #x軸數據 5 y1 = x*2 6 y2 = x**2 7 plt.figure(figsize=(5,3.5)) 8 plt.plot(x, y1,'r',marker='o',label='y1:double x') #關鍵句,前兩個參數是X、Y軸數據,其他參數指定曲線屬性,如標簽label,顏色color,線寬linewidth或lw,點標記marker 9 plt.plot(x,y2,'g',marker='^',label='y2:square of x') 10 plt.legend(loc='best') #顯示圖例,前提是plot參數里寫上label;loc是圖例的位置 11 plt.xlabel('x(ms)') 12 plt.ylabel('y') 13 plt.title('a simple example') 14 #plt.savefig('G:/YDPIC/example.png',dpi=80) #除了png,還有一些格式如svg,dpi是dot per inch每英寸的像素點數,缺省值80,論文寫作一般要求1200或者矢量圖 15 plt.show() #show函數顯示圖表會中斷程序,直到關閉圖像。不要把show寫在savefig前,否則保存圖像一片空白。最好是注釋掉savefig或者show其中一行。
matplotlib官網對plot的說明
二、面向對象方式繪圖
Figure對象,是一個“畫布或者容器” 的東西。如果用戶沒有寫plt.figure(),程序會自動創建一個Figure對象(圖像窗口)。 Axes是子圖,一個figure上可以有多個子圖,是具體作圖的區域。 Axis是坐標軸。關系如下圖。
在"一、簡單示例"的代碼中,plt幫我們隱藏了創建對象的過程,使用起來簡單,能滿足大部分作圖的需求。查看plt.plot的源碼發現ax = gca() 意思是get current axes獲取當前子圖,然后作圖都是調用的"ax"對象的方法。 當需要在一個figure上畫多子圖的時候,面向對象方式繪圖很好用。
給出幾個例子
繪制多子圖subplot
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 x = np.arange(0,5,0.01) 5 y1 = np.cos( 2*np.pi*x )*np.exp(-x) 6 y2 = np.cos( 2*np.pi*x ) 7 8 fig = plt.figure(facecolor='y') 9 10 ax1 = fig.add_subplot(211) #2行1列第1幅圖 11 ax1.plot(x, y1, '.-') 12 ax1.set_title('A table of 2 subplots') 13 ax1.set_ylabel('Damped oscillation') 14 15 ax2 = fig.add_subplot(212) #2行1列第2幅圖 16 ax2.plot(x,y2, '.-' ) 17 ax2.set_xlabel('time(s)') 18 ax2.set_ylabel('Undamped') 19 20 plt.show()
雙Y軸 ax2 = ax1.twinx()

import matplotlib.pyplot as plt import numpy as np x = np.arange(0.01,np.e, 0.01) y1 = np.exp(-x) y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y1,'r',label='exp(-x)') ax1.legend(bbox_to_anchor=(1,0.5)) ax1.set_ylabel('Y values for exp(-x)',color='r') ax1.set_xlabel('X values') ax1.set_title('Double Y axis') ax2 = ax1.twinx() ax2.plot(x,y2,'g',label='log(x)') ax2.legend(bbox_to_anchor=(1,0.6)) ax2.set_ylabel('Y values for log(x)',color='g') plt.show()
移動坐標軸spines

1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 fig = plt.figure(figsize=(4,4)) 5 ax = fig.add_subplot(111) 6 theta = np.arange(0, 2*np.pi, 2*np.pi/100) 7 x = np.cos(theta) 8 y = np.sin(theta) 9 ax.plot(x,y) 10 # top和right顏色置為none從而看不見 11 ax.spines['top'].set_color('none') 12 ax.spines['right'].set_color('none') 13 # spines的set_position函數,移動坐標軸位置 14 ax.spines['bottom'].set_position(('data',0)) 15 ax.spines['left'].set_position(('data',0)) 16 17 ax.xaxis.set_ticks([-1.2,1.2]) 18 ax.yaxis.set_ticks([-1.2,1.2]) 19 plt.show()
set_postion()函數 接收的參數是一個二元組tuple (postion type, amount) position type的取值可以有:'outward', 'axes','data'三種。本例中選擇了''data' amount取的0 就是數據坐標為0的位置。官網的解釋如下:
參考博客:
https://morvanzhou.github.io/tutorials/data-manipulation/plt/4-2-subplot2/
http://hyry.dip.jp/tech/book/page/scipy/matplotlib_fast_plot.html