Matlpotlib學(xué)習(xí)
- Matplotlib 是一個(gè)非常強(qiáng)大的 Python 畫(huà)圖工具翘悉。可以畫(huà)線圖居触、散點(diǎn)圖妖混、等高線圖、條形圖轮洋、柱狀圖制市、3D圖像、動(dòng)畫(huà)圖形等弊予。
一祥楣、基本使用
1.1 基本用法
- 流程
(1). 定義一個(gè)窗口,matplotlib.pyplot.figure
(2). 繪制曲線
(3). 顯示圖像汉柒,matplotlib.pyplot.show
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.figure()
plt.plot(x, y)
plt.show()
1.2 figure圖像
- matplotlib 的 figure 就是一個(gè) 單獨(dú)的 figure 小窗口, 小窗口里面還可以有更多的小圖片误褪。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure(num=3, figsize=(8, 5)) #num設(shè)置窗口編號(hào),figsize設(shè)置窗口大小
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') #linewidth:線寬碾褂,linestyle:線的風(fēng)格
plt.show()
1.3 設(shè)置坐標(biāo)軸
- matplotlib.pyplot.xlabel:設(shè)置x坐標(biāo)軸名稱
- matplotlib.pyplot.ylabel:設(shè)置y坐標(biāo)軸名稱
- matplotlib.pyplot.xlim:設(shè)置x坐標(biāo)軸范圍
- matplotlib.pyplot.ylim:設(shè)置y坐標(biāo)軸范圍
- matplotlib.pyplot.xticks:設(shè)置x軸刻度
- matplotlib.pyplot.yticks:設(shè)置y軸刻度以
- matplotlib.pyplot.gca:獲取當(dāng)前坐標(biāo)軸信息
- matplotlib.pyplot..spines:設(shè)置邊框
- .xaxis.set_ticks_position:設(shè)置x坐標(biāo)刻度數(shù)字或名稱的位置,默認(rèn)bottom.(所有位置:top兽间,bottom,both斋扰,default渡八,none)
- .yaxis.set_ticks_position:設(shè)置y坐標(biāo)刻度數(shù)字或名稱的位置,默認(rèn)left.(所有位置:left啃洋,right,both屎鳍,default宏娄,none)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
*使用plt.yticks設(shè)置y軸刻度以及名稱:刻度為[-2, -1.8, -1, 1.22, 3];對(duì)應(yīng)刻度的名稱為[‘really bad’,’bad’,’normal’,’good’, ‘really good’].
*plt.yticks([-2, -1.8, -1, 1.22, 3],[r'', r'
', r'
', r'
', r'
']),兩個(gè)$符號(hào)種的字母的字體會(huì)改變逮壁,兩個(gè)$中空格顯示不出來(lái)孵坚,需要用轉(zhuǎn)置符\.
1.4 Legend圖例
- matplotlib 中的 legend 圖例就是為了幫我們展示出每個(gè)數(shù)據(jù)對(duì)應(yīng)的圖像名稱. 更好的讓讀者認(rèn)識(shí)到你的數(shù)據(jù)結(jié)構(gòu)。
- 使用legend需要對(duì)窗中的每個(gè)圖設(shè)置lable窥淆。如果不用自己的lable需要使用handles這個(gè)參數(shù)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
#set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# set line syles
l1, = plt.plot(x, y1, label='linear line') #l1, l2,要以逗號(hào)結(jié)尾, 因?yàn)閜lt.plot() 返回的是一個(gè)列表
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(loc='upper right')#參數(shù) loc='upper right' 表示圖例將添加在圖中的右上角
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
put.show()
loc的可選值:
'best' : 0,
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
1.5 Annotation標(biāo)注
*annotate參數(shù)說(shuō)明:
調(diào)用簽名:plt.annotate(string, xy=(np.pi/2, 1.0), xytext=((np.pi/2)+0.15, 1,5), weight="bold", color="b", arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="b"))
- string:圖形內(nèi)容的注釋文本
- xy:被注釋圖形內(nèi)容的位置坐標(biāo)
- xytext:注釋文本的位置坐標(biāo)
- weight:注釋文本的字體粗細(xì)風(fēng)格
- color:注釋文本的字體顏色
- arrowprops:指示被注釋內(nèi)容的箭頭的屬性字典
matploylib.pylot.text()也可以添加注釋
調(diào)用簽名:
ext(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
- x,y:表示坐標(biāo)值上的值
- string:表示說(shuō)明文字
- fontsize:表示字體大小
- verticalalignment:垂直對(duì)齊方式 卖宠,參數(shù):[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
- horizontalalignment:水平對(duì)齊方式 ,參數(shù):[ ‘center’ | ‘right’ | ‘left’ ]
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y)
#移動(dòng)坐標(biāo)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#畫(huà)虛線和點(diǎn)
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
#添加注釋annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) #xycoords='data' 是說(shuō)基于數(shù)據(jù)的值來(lái)選位置
#添加注釋text
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
1.6 tick能見(jiàn)度
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
# 在 plt 2.0.2 或更高的版本中, 設(shè)置 zorder 給 plot 在 z 軸方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#調(diào)整能見(jiàn)度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
# 在 plt 2.0.2 或更高的版本中, 設(shè)置 zorder 給 plot 在 z 軸方向排序
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()
二忧饭、畫(huà)圖種類
(1)散點(diǎn)圖
函數(shù)原型:matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, data=None, **kwargs)
參數(shù)解釋:
- x扛伍,y:表示的是大小為(n,)的數(shù)組,也就是我們即將繪制散點(diǎn)圖的數(shù)據(jù)點(diǎn)
- s:是一個(gè)實(shí)數(shù)或者是一個(gè)數(shù)組大小為(n,)词裤,這個(gè)是一個(gè)可選的參數(shù)刺洒。
- c:表示的是顏色,也是一個(gè)可選項(xiàng)吼砂。默認(rèn)是藍(lán)色'b',表示的是標(biāo)記的顏色逆航,或者可以是一個(gè)表示顏色的字符,或者是一個(gè)長(zhǎng)度為n的表示顏色的序列等等渔肩,感覺(jué)還沒(méi)用到過(guò)現(xiàn)在不解釋了因俐。但是c不可以是一個(gè)單獨(dú)的RGB數(shù)字,也不可以是一個(gè)RGBA的序列周偎∧ㄊ#可以是他們的2維數(shù)組(只有一行)。
- marker:表示的是標(biāo)記的樣式栏饮,默認(rèn)的是'o'吧兔。
- cmap:Colormap實(shí)體或者是一個(gè)colormap的名字磷仰,cmap僅僅當(dāng)c是一個(gè)浮點(diǎn)數(shù)數(shù)組的時(shí)候才使用袍嬉。如果沒(méi)有申明就是image.cmap
- norm:Normalize實(shí)體來(lái)將數(shù)據(jù)亮度轉(zhuǎn)化到0-1之間,也是只有c是一個(gè)浮點(diǎn)數(shù)的數(shù)組的時(shí)候才使用灶平。如果沒(méi)有申明伺通,就是默認(rèn)為colors.Normalize。
- vmin,vmax:實(shí)數(shù)逢享,當(dāng)norm存在的時(shí)候忽略罐监。用來(lái)進(jìn)行亮度數(shù)據(jù)的歸一化。
- alpha:實(shí)數(shù)瞒爬,0-1之間弓柱。
import matplotlib.pyplot as plt
import numpy as np
n = 1024 # data size
X = np.random.normal(0, 1, n) # 每一個(gè)點(diǎn)的X值
Y = np.random.normal(0, 1, n) # 每一個(gè)點(diǎn)的Y值
T = np.arctan2(Y,X) # for color value
plt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticks
plt.show()
(2)柱狀圖
函數(shù)原型:bar(x, height, width=0.8, bottom=None, , align='center', data=None, kwargs*)
參數(shù)說(shuō)明:
參數(shù) | 說(shuō)明 | 類型 |
---|---|---|
x | x坐標(biāo) | int,float |
height | 條形的高度 | int,float |
width | 寬度 | 0~1沟堡,默認(rèn)0.8 |
botton | 條形的起始位置 | 也是y軸的起始坐標(biāo) |
align | 條形的中心位置 | “center”,"lege"邊緣 |
color | 條形的顏色 | “r","b","g","#123465",默認(rèn)“b" |
edgecolor | 邊框的顏色 | 同上 |
linewidth | 邊框的寬度 | 像素矢空,默認(rèn)無(wú)航罗,int |
tick_label | 下標(biāo)的標(biāo)簽 | 可以是元組類型的字符組合 |
log | y軸使用科學(xué)計(jì)算法表示 | bool |
orientation | 是豎直條還是水平條 | 豎直:"vertical",水平條:"horizontal" |
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, +Y1)
plt.bar(X, -Y2)
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
#加顏色
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
#加數(shù)據(jù)
for x, y in zip(X, Y1):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
plt.show()
(3)等高線圖
函數(shù)原型:contour([X, Y,] Z, [levels], **kwargs)
,具體見(jiàn)官方文檔
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
# the height function
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y) #定義網(wǎng)格
#使用函數(shù)plt.contourf把顏色加進(jìn)去
# use plt.contourf to filling contours
# X, Y and value for (X,Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
#使用plt.contour函數(shù)劃線
# use plt.contour to add contour lines
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
#添加高度數(shù)字
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show
(4)image圖片
*隨即矩陣畫(huà)圖屁药,這里我們打印出的是純粹的數(shù)字粥血,而非自然圖像。
import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
#添加colorbar
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
interpolation的取直參見(jiàn)官方網(wǎng)站
(5)3D數(shù)據(jù)
- 首先要從mpl_toolkits.mplot3d導(dǎo)入Axes3D
- 然后ax = Axes3D(fig)
- 使用ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))繪圖
- 使用ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))畫(huà)投影
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y) # x-y 平面的網(wǎng)格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
#投影
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2,2)
put.show()
三酿箭、多圖合并顯示
3.1 subplot多合一顯示
- 均勻圖中圖
import matplotlib.pyplot as plt
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,2])
plt.subplot(223)
plt.plot([0,1],[0,3])
plt.subplot(224)
plt.plot([0,1],[0,4])
plt.figure()
- 不均勻圖中圖
import matplotlib.pyplot as plt
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(235)
plt.plot([0,1],[0,3])
plt.subplot(236)
plt.plot([0,1],[0,4])
plt.figure()
3.2 subplot分格顯示
- 方法一:subplot2grid
- 方法二:gridspec
- 方法三:subplots
#method 1:subplot2grid
import matplotlib.pyplot as plt
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)#colspan=3表示列的跨度為3, rowspan=1表示行的跨度為1复亏。默認(rèn)值都為1.
ax1.plot([1, 2], [1, 2]) # 畫(huà)小圖
ax1.set_title('ax1_title') # 設(shè)置小圖的標(biāo)題
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
plt.show()
#method 2:gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3) #將整個(gè)圖像窗口分成3行3列
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
###method 3:subplots
f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()
3.3 圖中圖
# 導(dǎo)入pyplot模塊
import matplotlib.pyplot as plt
# 初始化figure
fig = plt.figure()
# 創(chuàng)建數(shù)據(jù)
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
#大圖
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 #首先確定大圖左下角的位置以及寬高,注意缭嫡,4個(gè)值都是占整個(gè)figure坐標(biāo)系的百分比
#將大圖坐標(biāo)系添加到figure中缔御,顏色為r(red),取名為title
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
#小圖:步驟和繪制大圖一樣妇蛀,注意坐標(biāo)系位置和大小的改變
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
#采用一種更簡(jiǎn)單方法畫(huà)小圖刹淌,即直接往plt里添加新的坐標(biāo)系
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意對(duì)y進(jìn)行了逆序處理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
3.4 次坐標(biāo)軸
#第一個(gè)坐標(biāo)軸
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
#第二個(gè)坐標(biāo)軸
ax2 = ax1.twinx() #對(duì)ax1調(diào)用twinx()方法,生成如同鏡面效果后的ax2
ax1.plot(x, y1, 'g-') # green, solid line
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.plot(x, y2, 'b-') # blue
ax2.set_ylabel('Y2 data', color='b')
plt.show()
四讥耗、動(dòng)畫(huà)
- 調(diào)用FuncAnimation函數(shù)生成動(dòng)畫(huà)有勾。參數(shù)說(shuō)明:
參數(shù) 描述 fig 進(jìn)行動(dòng)畫(huà)繪制的figure func 自定義動(dòng)畫(huà)函數(shù),即傳入剛定義的函數(shù)animate frames 動(dòng)畫(huà)長(zhǎng)度古程,一次循環(huán)包含的幀數(shù) init_func 自定義開(kāi)始幀蔼卡,即傳入剛定義的函數(shù)init interval 更新頻率,以ms計(jì) blit 選擇更新所有點(diǎn)挣磨,還是僅更新產(chǎn)生變化的點(diǎn)雇逞。應(yīng)選擇True,但mac用戶 請(qǐng)選擇False茁裙,否則無(wú)法顯示動(dòng)畫(huà)
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
#構(gòu)造自定義動(dòng)畫(huà)函數(shù)animate塘砸,用來(lái)更新每一幀上各個(gè)x對(duì)應(yīng)的y坐標(biāo)值,參數(shù)表示第i幀
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.sin(x ))
return line,
#構(gòu)造開(kāi)始幀函數(shù)init
ani = animation.FuncAnimation(fig=fig,
func=animate,
frames=100,
init_func=init,
interval=20,
blit=False)
plt.show()