matplotlib畫圖簡(jiǎn)單例子學(xué)習(xí)
Tips:該文帶目錄地址http://www.cloboy.top/index.php/archives/124/
1. 看圖識(shí)大局
首先看看一張圖像的構(gòu)成,上面一幅圖足夠解釋各個(gè)部分的名稱功能裳瘪,下面解釋幾個(gè)不好理解的部分
- Figure:可以看成一張幕布菌湃,在上面你可以畫多張圖像
- Axes:當(dāng)前畫一張圖像的區(qū)域
- Spines:其實(shí)就是連接軸刻度標(biāo)記的那些直線
- Makers:標(biāo)記點(diǎn)油啤,用于只畫點(diǎn)而不畫線的圖像
該大圖的每一部分在matplotlib中都可以進(jìn)行修改和調(diào)整灰署。下面看幾個(gè)例子學(xué)習(xí)把润樱。瑰剃。
2.畫一張功能齊全的圖
A.顯示圖像
B.對(duì)應(yīng)代碼
import matplotlib.pyplot as plt #matplotlib畫圖函數(shù)
import numpy as np #加載numpy模塊
x = np.linspace(0, 2, 100) #0到2之間取100個(gè)數(shù)
plt.plot(x, x, label='linear') #(x坐標(biāo)歪沃,y坐標(biāo)臣淤,名稱標(biāo)記)
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label') #橫軸名稱
plt.ylabel('y label') #縱軸名稱
plt.title("Simple Plot") #整張圖像的title
plt.legend() #將plot函數(shù)中的label展示出來(lái):展示圖例橄霉,可加入?yún)?shù)對(duì)圖例的位置等進(jìn)行調(diào)整
plt.show() #展示圖像
3.一張幕布下畫兩張圖
我們?nèi)绻朐谝粡埬徊枷拢╢ig下)畫兩張甚至更多不同的圖像,就可參考一下案例
A.顯示圖像
B.對(duì)應(yīng)代碼
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, [ax1,ax2] = plt.subplots(2,1) #幕布大小為2*1, [ax1,ax2] 可以用ax替代邑蒋,相應(yīng)的ax1和ax2可以分別用ax[0]和ax[1]替代
ax1.plot(x, y) #ax1 = ax[0]
ax1.set_xlabel('time') #設(shè)置橫軸名稱
ax1.set_ylabel('high') #設(shè)置縱軸名稱
ax2.plot(x,y) #ax2 = ax[1]
ax2.set_title('sinB') #設(shè)置標(biāo)題
ax2.set_ylabel('high')#設(shè)置橫軸名稱
ax2.set_xlabel('time')#設(shè)置縱軸名稱
#注意兩張圖像描繪與單張圖像時(shí)設(shè)置label和title的區(qū)別
fig.tight_layout() #自動(dòng)調(diào)整兩種圖像的距離姓蜂,使得兩者不出現(xiàn)重疊,可以自行去掉會(huì)發(fā)現(xiàn)兩天出現(xiàn)重疊医吊,不美觀
plt.show()
4.給圖像中的線加入散點(diǎn)
我們經(jīng)常會(huì)在論文里看到下面這樣的圖像钱慢,那這樣的線得怎么畫呢?
A.顯示圖像
B.對(duì)應(yīng)代碼
import matplotlib.pyplot as plt #導(dǎo)入matplotlib函數(shù)
import numpy as np
def f(t):
'一個(gè)阻尼系數(shù)函數(shù)'
s1 = np.cos(2 * np.pi * t)
e1 = np.exp(-t)
return s1 * e1
t1 = np.arange(0.0, 5.0, .2) #時(shí)間軸
da = plt.plot(t1, f(t1),marker = 'o',label = 'damp')#marker表示每個(gè)點(diǎn)在另外用'o'來(lái)標(biāo)記卿堂,如果不加marker = 束莫,那么該圖像只有散點(diǎn),沒(méi)有線條
plt.setp(da, markersize=10) #設(shè)置da對(duì)象中標(biāo)記點(diǎn)的屬性草描,將marker的大小設(shè)置為10
plt.legend() #展示圖例
plt.show()
附錄:貼出部分marker的屬性
5.設(shè)置坐標(biāo)范圍及開(kāi)啟網(wǎng)格線
A.展示圖像
B.對(duì)應(yīng)代碼
import matplotlib.pyplot as plt #matplotlib畫圖函數(shù)
import numpy as np #加載numpy模塊
x = np.arange(0, 10, 0.2)
y = np.sin(x)
plt.plot(x, y, label='linear')
plt.xlim([-1,11]) # 設(shè)置x軸邊界范圍
plt.ylim([-2,2]) # 設(shè)置y軸邊界范圍
plt.grid(True)
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3) #設(shè)置網(wǎng)格的一些參數(shù)览绿,根據(jù)各個(gè)參數(shù)的英文可知其作用
plt.legend(loc='lower right') #讓圖例的位置位于右下方
plt.show()
附錄:貼出legend的位置設(shè)置