python中的matplotlib庫入門
阿新 • • 發佈:2018-12-04
python中的matplotlib庫入門
matplotlib.pyplot是繪製各類視覺化圖形的命令子庫,相當於快捷方式
一.引入方式
import matplotlib.pyplot as plt
二.plt.plot()函式
plt.plot(x, y, format_string, **kwargs)
- x : X軸資料,列表或陣列,可選
- y : Y軸資料,列表或陣列
- format_string : 控制曲線的格式字串,可選
- **kwargs : 第二組或更多(x,y,format_string)
a = np.arange(0.0,5.0,0.01)
plt.plot(a,np.sin(2*np.pi*a),'r--',a,np.cos(2*np.pi*a),a,np.sinc(a),a,np.cosh(a))
plt.show()
format_string
顏色字元
顏色字元 | 含義 | 顏色字元 | 含義 |
---|---|---|---|
’b’ | 藍色 | ’m’ | 洋紅色 magenta |
’g’ | 綠色 | ’y’ | 黃色 |
’r’ |
紅色 | ’k’ | 黑色 |
’c’ | 青綠色 cyan | ’w’ | 白色 |
風格字元
風格字元 | 含義 |
---|---|
’‐' | 實線 |
’‐‐' | 破折線 |
’‐.' | 點劃線 |
’:' | 虛線 |
’ ’ ’ ' | 無線條 |
標記字元
標記字元 | 含義 | 標記字元 | 含義 | 標記字元 | 含義 |
---|---|---|---|---|---|
‘.’ | 點標記 | ‘1’ 下花三角標記 | ‘h’ | 豎六邊形標記 | |
‘,’ | 畫素標記(極小點) | ‘2’ | 上花三角標記 | ‘H’ 橫六邊形標記 | |
‘o’ | 實心圈標記 | ‘3’ | 左花三角標記 | ‘+’ | 十字標記 |
‘v’ | 倒三角標記 | ‘4’ | 右花三角標記 | ‘x’ | x標記 |
‘^’ | 上三角標記 | ‘s’ | 實心方形標記 | ‘D’ | 菱形標記 |
‘>’ | 右三角標記 | ‘p’ | 實心五角標記 | ‘d’ | 瘦菱形標記 |
‘<’ | 左三角標記 | ‘*’ | 星形標記 | '|' |
垂直線標記 |
三.pyplot的繪圖區域
plt.subplot(nrows, ncols, plot_number)
# 第一個引數為使用行將平面分為幾個區域,
# 第二個引數為使用列將平面分為幾個區域,
# 第三個引數為定位所要繪製的區域,從左上角開始向右數,
上圖即位plt.subplot(3,2,x)的示意圖
def func(t):
return np.exp(-t) * np.exp(2*np.pi*t)
a = np.arange(0.0,5.0,0.02)
plt.subplot(211)
plt.plot(a,func(a))
plt.subplot(212)
plt.plot(a,np.sinc(2*np.pi*a),'r--')
plt.show()
plot()函式,a,np.sinc(a),a,np.cosh(a),a,np.exp(a)
四.plotpy的文字顯示
文字顯示函式
函式 | 含義 |
---|---|
plt.xlabel() | 對X軸增加文字標籤 |
plt.ylabel() | 對Y軸增加文字標籤 |
plt.title() | 對圖形整體增加文字標籤 |
plt.text() | 在任意位置增加文字 |
plt.annotate() | 在圖形中增加帶箭頭的註解 |
a = np.arange(0.0,5.0,0.01)
plt.plot(a,np.cos(2*np.pi*a),'c--')
plt.ylabel("y")
plt.xlabel("x")
plt.title(r"$y=cos(2\pi x)$") # $ $為Latex顯示方法
plt.text(2,1,r'$\mu=100$')
plt.axis([-1,7,-2,2]) # x與y座標軸的極限值
plt.grid(True) # 是否有網格
plt.show()
將plt.text(2,1,r'$\mu=100$')
替換為plt.annotate(r'$\mu=100$', xy=(2,1), xytext=(3.3,1.5),arrowprops=dict(facecolor='black',shrink=0.1,width=0.5))
則會有以下效果