最后一次更新日期: 2019/4/20
Matplotlib 是一個(gè) Python 的 2D繪圖庫(kù),它以各種硬拷貝格式和跨平臺(tái)的交互式環(huán)境生成出版質(zhì)量級(jí)別的圖形。
按需導(dǎo)入以下模塊:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
此篇為匯總,點(diǎn)擊下方鏈接可前往各小節(jié)
簡(jiǎn)要使用教程1 - 繪圖結(jié)構(gòu) (圖像,坐標(biāo)軸/子圖,顯示,保存)
簡(jiǎn)要使用教程2 - 繪圖設(shè)置 (投影類(lèi)型,字體,顏色,標(biāo)題,坐標(biāo)軸,圖例,標(biāo)記樣式,線(xiàn)條樣式,透明度,旋轉(zhuǎn),子圖布局)
簡(jiǎn)要使用教程3 - 常用繪圖類(lèi)型(散點(diǎn)圖,曲線(xiàn)圖,曲面圖,條形圖,直方圖,餅圖/環(huán)圖,箱線(xiàn)圖,等高線(xiàn)圖,極坐標(biāo)圖)
簡(jiǎn)要使用教程4 - 其他繪圖元素(注解,填充,圖片,基本圖形,數(shù)據(jù)表格)
也可以看看:
numpy使用指南
pandas簡(jiǎn)要使用教程
一. 繪圖結(jié)構(gòu)
1. 圖像figure
In [71]: fig=plt.figure(1)
<Figure size 432x288 with 0 Axes>
In [72]: fig=plt.figure(2,figsize=(5,3))
<Figure size 360x216 with 0 Axes>
In [73]: fig.suptitle('title')
Out[73]: Text(0.5,0.98,'title')
Figure
是所有繪圖元素的頂級(jí)容器,可以認(rèn)為是一張畫(huà)布,第一個(gè)參數(shù)num
設(shè)置圖像的編號(hào),第二個(gè)figsize
參數(shù)設(shè)置圖像大小。
Figure.suptitle
方法用于設(shè)置圖像的總標(biāo)題(也可通過(guò)plt.suptitle
設(shè)置),fontsize
參數(shù)可以設(shè)置字體大小,x
和y
參數(shù)設(shè)置位置坐標(biāo),取值為0.~1.的相對(duì)于Figure
的寬和高的比例。
Figure
上無(wú)法直接繪圖,需要至少添加一個(gè)Axes
,在調(diào)用plt
的靜態(tài)方法繪圖時(shí),會(huì)繪制在最近聲明的一個(gè)Figure
上,不顯示聲明則會(huì)自動(dòng)按默認(rèn)配置創(chuàng)建Figure
和Axes
,plt.gcf()
方法可以獲取當(dāng)前正在繪制的Figure
。
Figure.axes
可以獲取圖像下的所有Axes
;
Figure.clf()
方法可以清空?qǐng)D像。
Artist
是matplotlib中所有繪圖對(duì)象的基類(lèi),Figure
也是繼承自該類(lèi),可在官方文檔查看到完整的繼承關(guān)系。
2. 坐標(biāo)軸axes
x=np.arange(0,720,1)
y1=np.sin(x*np.pi/180)
y2=np.cos(x*np.pi/180)
#方法1
fig=plt.figure(figsize=(7.5,3))
fig.suptitle('sin/cos',fontsize=16)
ax=fig.add_axes((0,0,0.5,0.8),title='ax1')
ax.plot(x,y1)
ax=fig.add_axes((0.6,0,0.5,0.8),title='ax2')
ax.plot(x,y2)
plt.show(fig)
#方法2
fig=plt.figure(figsize=(10.5,3))
fig.suptitle('sin/cos',fontsize=16)
ax=fig.add_subplot(121,title='ax1', projection='3d')
ax.plot(x,y1)
ax=fig.add_subplot(122,title='ax2', projection='3d')
ax.plot(x,y2)
plt.show(fig)
Axes
的意思是用于繪圖的坐標(biāo)軸,AxesSubplot
是封裝了Axes
的子圖,通過(guò)不同的方法創(chuàng)建,子圖在布局上更方便,繪圖時(shí)則沒(méi)有明顯的區(qū)別,下面會(huì)將Axes
也稱(chēng)作子圖。
繪制不同圖像會(huì)使用不同軸類(lèi)型,最常用的xy坐標(biāo)軸和xyz坐標(biāo)軸分別為Axes
和Axes3D
。如果只需要一個(gè)Axes
,可以不顯示聲明,直接調(diào)用plt
的靜態(tài)方法繪制,Axes
會(huì)被自動(dòng)創(chuàng)建(通過(guò)add_subplot(111)
)。當(dāng)存在多個(gè)Axes
時(shí),可以調(diào)用Axes
的方法繪圖以保證圖像被繪制在正確的子圖上,調(diào)用靜態(tài)方法繪制時(shí)實(shí)際上是通過(guò)plt.gca()
獲取了最后聲明的Axes
。
Axes.plot
是繪圖方法,用于繪制曲線(xiàn)圖。
Axes
在繪圖時(shí)需要提供x,y兩個(gè)軸的坐標(biāo),而Axes3D
需要提供x,y,z三個(gè)軸的坐標(biāo),上方的例子中沒(méi)有提供z軸坐標(biāo)所以圖像被繪制在高度為0的一個(gè)平面上。
Axes
是綁定在Figure
上的,可通過(guò)調(diào)用Figure
的add_axes
或add_subplot
方法創(chuàng)建新的Axes
或是將已有Axes
添加到Figure
上。兩種方法在子圖的大小和位置的設(shè)置上有所區(qū)別,需要相應(yīng)的調(diào)整參數(shù)。
add_axes
方法的第一個(gè)參數(shù)rect
通過(guò)一個(gè)浮點(diǎn)數(shù)序列設(shè)置Axes
的位置和大小,格式為(left,bottom,width,height)
,值均為0.~1.的相對(duì)于Figure
的寬和高的比例。
add_subplot
方法的前三個(gè)參數(shù)分別設(shè)置區(qū)間劃分的行數(shù)、列數(shù)、以及子圖的索引,例如2,3,5
表示將Figure
劃分為2行3列,在其中第5個(gè)區(qū)間上添加子圖;前三個(gè)參數(shù)可以替換為單個(gè)3位整數(shù)表示同一含義,但每位的值不得超過(guò)10,例如2,3,5
對(duì)應(yīng)235
。
title
參數(shù)用于設(shè)置子圖的標(biāo)題,也可通過(guò)Axes.set_title
或plt.title
方法設(shè)置;
projection
參數(shù)設(shè)置投影類(lèi)型,即坐標(biāo)軸類(lèi)型,其中,'rectilinear'
表示直線(xiàn)(xy)坐標(biāo)軸,也是默認(rèn)值,'3d'
表示3D(xyz)坐標(biāo)軸。
除以上兩種方法,還可使用fig,ax_list = plt.subplots(figsize=(10.5,3),ncols=2,nrows=1)
快速規(guī)劃畫(huà)布,只需要指定畫(huà)布大小、列劃分?jǐn)?shù)量和行劃分?jǐn)?shù)量,省去寫(xiě)循環(huán)的時(shí)間。
get_children
方法能夠獲取Axes
下的所有繪圖元素;
collections
屬性能夠獲取所有繪圖元素集合;
如想獲取指定類(lèi)型的元素,可使用get_xlabel
等方法;
cla
方法可以清除當(dāng)前軸的內(nèi)容。
3. 顯示show
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()
plt.plot(x,y1)
plt.show()
plt.plot(x,y2)
plt.show()
plt.show()
方法用于顯示已繪制的圖像,一般配合plt
的靜態(tài)繪圖方法使用(即不顯示聲明Figure
的情況)。在使用靜態(tài)方法繪圖時(shí),如果不調(diào)用show
,則代碼段的中所有繪圖元素將會(huì)繪制在自動(dòng)創(chuàng)建的同一Figure
的同一Axes
上。
在ipython中,直接輸入Figure
的變量名也可以將其圖像顯示出來(lái);在執(zhí)行一段含繪圖語(yǔ)句的代碼段后,也會(huì)自動(dòng)顯示圖像。
4. 保存save
fig.savefig('D:\\test.jpg')
Figure
的savefig
方法可以保存圖片至指定路徑,也可調(diào)用plt
的靜態(tài)方法保存,但必須和繪圖的代碼一起執(zhí)行,且必須在show
方法之前執(zhí)行。
ipython中直接右鍵顯示出來(lái)的圖片也有保存的選項(xiàng)。
二. 繪圖設(shè)置
1. 投影projection
projection
參數(shù)用于設(shè)置生成的Axes
類(lèi)型,在add_axes
、add_subplot
等方法中可使用。
常用的幾個(gè)類(lèi)型:
'rectilinear'
:直線(xiàn)坐標(biāo)軸,即2d的xy坐標(biāo)軸,默認(rèn)值;
'3d'
:3D的xyz坐標(biāo)軸,繪制3d圖像會(huì)使用這個(gè),注意,使用該類(lèi)型前必須先導(dǎo)入Axes3D
;
'polar'
:極坐標(biāo)軸。
2. 字體font
plt.rcParams['font.sans-serif']
屬性用于設(shè)置默認(rèn)字體,當(dāng)圖像中中文顯示存在問(wèn)題時(shí),可通過(guò)該項(xiàng)將字體設(shè)置為支持中文的字體,例如['SimHei']
黑體;
plt.rcParams['font.size']
屬性用于設(shè)置默認(rèn)字體大小。
也可以?xún)H在特定文本上應(yīng)用字體,fontsize
參數(shù)設(shè)置字體大小,fontproperties
參數(shù)設(shè)置字體,在suptitle
、set_title
、text
等用于定義文字顯示的方法中可使用。
當(dāng)負(fù)號(hào)無(wú)法正常顯示時(shí),設(shè)置plt.rcParams['axes.unicode_minus']=False
。
3. 顏色color
多以color
或colors
參數(shù)設(shè)置主體顏色或顏色序列,簡(jiǎn)寫(xiě)形式c
,也有單獨(dú)設(shè)置某個(gè)部分顏色的參數(shù):facecolor
設(shè)置填充顏色,簡(jiǎn)寫(xiě)形式fc
;edgecolor
設(shè)置邊緣顏色,簡(jiǎn)寫(xiě)形式ec
。
支持多種標(biāo)識(shí)顏色的方式:
(1). 以tuple
表示的RGB或RGBA值,取值范圍在0.~1.,例如(0.1,0.2,0.5)
;
(2). 以str
表示的16進(jìn)制的RGB或RGBA值,取值范圍00~FF,例如'#0F0F0F'
;
(3). 以str
表示的顏色標(biāo)簽,可參考下圖(官方示例)。
除了單個(gè)顏色外,matplotlib還提供了colormap,是特定主題的顏色集合,一般通過(guò)cmap
參數(shù)設(shè)置,而預(yù)定義的colormap在plt.cm
下,可用種類(lèi)詳見(jiàn)官方文檔。
4. 標(biāo)題title
Figure.suptitle
或plt.suptitle
方法用于設(shè)置總標(biāo)題;
Axes.set_title
或plt.title
方法以及創(chuàng)建Axes
時(shí)的title
參數(shù)用于設(shè)置子標(biāo)題。
5. 坐標(biāo)軸axis
xlabel
、ylabel
、zlabel
等方法用于設(shè)置坐標(biāo)軸的標(biāo)簽;
xticks
、yticks
、zticks
等方法用于設(shè)置坐標(biāo)軸的刻度,傳入?yún)?shù)為刻度值列表和刻度標(biāo)簽列表,第二個(gè)參數(shù)可以省略,會(huì)以刻度值作為標(biāo)簽文字;
xlim
、ylim
、zlim
等方法用于設(shè)置坐標(biāo)軸的范圍,傳入?yún)?shù)為開(kāi)始值和結(jié)束值;
axis('off')
可以關(guān)閉坐標(biāo)軸顯示;
以上方法可通過(guò)plt
調(diào)用,Axes
則需要通過(guò)set_xlabel
等方法調(diào)用。
6. 圖例legend
plt.plot(x,y1,label='sin')
plt.plot(x,y2,label='cos')
plt.legend()
plt.show()
legend
方法用于顯示圖例,繪圖元素必須有標(biāo)簽才能正常生成圖例,可在繪制圖像時(shí)通過(guò)label
參數(shù)設(shè)置標(biāo)簽,或是調(diào)用legend
方法時(shí)傳入標(biāo)簽列表。
loc
參數(shù)設(shè)置圖例的位置,默認(rèn)'best'
自動(dòng)選擇。
7. 標(biāo)記樣式marker
參數(shù)marker
設(shè)置標(biāo)記樣式,可選的樣式參考官方文檔-markers;
參數(shù)s
或markersize
設(shè)置標(biāo)記大小。
標(biāo)記樣式可在散點(diǎn)圖、曲線(xiàn)圖等中設(shè)置。
8. 線(xiàn)條樣式linestyle
參數(shù)linestyle
設(shè)置線(xiàn)條樣式,一般默認(rèn)'-'
實(shí)線(xiàn),可選的樣式見(jiàn)下方表格;
參數(shù)linewidth
設(shè)置線(xiàn)的寬度,簡(jiǎn)寫(xiě)形式lw
。
linestyle | 說(shuō)明 |
---|---|
'-' or 'solid' | 實(shí)線(xiàn) |
'--' or 'dashed' | 虛線(xiàn) |
'-.' or 'dashdot' | 點(diǎn)劃線(xiàn) |
':' or 'dotted' | 點(diǎn)虛線(xiàn) |
'None' or '' | 不繪制 |
線(xiàn)條樣式在所有含線(xiàn)條的繪圖對(duì)象中幾乎都可以設(shè)置。
9. 透明度alpha
參數(shù)alpha
設(shè)置點(diǎn)的透明度,一般默認(rèn)1.
,值越小透明度越高。
透明度在所有含平面的繪圖對(duì)象中幾乎都可以設(shè)置。
10. 旋轉(zhuǎn)rotation
繪圖元素旋轉(zhuǎn)
fig=plt.figure(figsize=(4.5,3))
ax=fig.add_axes((0,0,1,1))
ax.plot(x,y1)
for tick in ax.get_xticklabels():
tick.set_rotation(90)
部分繪圖元素是支持旋轉(zhuǎn)的,可通過(guò)set_rotation
方法設(shè)置或是創(chuàng)建時(shí)通過(guò)rotation
參數(shù)設(shè)置,也有通過(guò)angle
參數(shù)控制旋轉(zhuǎn)的。
3D圖像旋轉(zhuǎn)
fig=plt.figure(figsize=(12,3))
ax=fig.add_subplot(131,title='ax1',projection='3d')
ax.plot(x,y1)
ax=fig.add_subplot(132,title='ax2',projection='3d')
ax.view_init(30,80)
ax.plot(x,y1)
ax=fig.add_subplot(133,title='ax3',projection='3d')
ax.view_init(60,120)
ax.plot(x,y1)
Axes3D
的旋轉(zhuǎn)通過(guò)view_init
方法實(shí)現(xiàn),第一個(gè)參數(shù)elev
控制縱向的旋轉(zhuǎn)角度,默認(rèn)值30;第二個(gè)參數(shù)azim
控制橫向的旋轉(zhuǎn)角度,默認(rèn)值120。
11. 子圖布局調(diào)整adjust
#自動(dòng)收縮布局
fig.tight_layout()
#調(diào)整子圖分布
fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1)
三. 常用繪圖類(lèi)型
1. 散點(diǎn)圖
n = 100
x = np.random.randn(n)
y = np.random.randn(n)
z = np.random.randn(n)
fig=plt.figure(figsize=(9,3))
ax=fig.add_subplot(121,title='2d scatter')
ax.scatter(x,y,s=100,c=['g','r','y'],marker='*',alpha=0.5,linewidths=1,edgecolor='k')
ax=fig.add_subplot(122,title='3d scatter',projection='3d')
ax.scatter(x,y,z)
plt.show()
scatter
方法用于繪制散點(diǎn)圖:
參數(shù)s
設(shè)置點(diǎn)的大小(面積),默認(rèn)20
;
參數(shù)c
設(shè)置點(diǎn)的顏色,可以是單個(gè)也可以多個(gè),默認(rèn)'b'
藍(lán)色;
參數(shù)marker
設(shè)置點(diǎn)的樣式,默認(rèn)'o'
圓;
參數(shù)alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.
,值越小透明度越高;
參數(shù)linewidths
設(shè)置邊緣線(xiàn)的寬度,默認(rèn)None
;
參數(shù)edgecolor
設(shè)置邊緣線(xiàn)的顏色,默認(rèn)None
。
2. 曲線(xiàn)圖
n = 100
x = np.arange(0,8*n,8)
y = np.sin(x*np.pi/180)
z = np.cos(x*np.pi/180)
fig=plt.figure(figsize=(9,3))
ax=fig.add_subplot(121,title='2d plot')
ax.plot(x,y,'g<-',alpha=0.5,linewidth=2, markersize=8)
ax=fig.add_subplot(122,title='3d plot',projection='3d')
ax.plot(x,y,z)
plt.show()
plot
方法用于繪制散點(diǎn)圖:參數(shù)
fmt
設(shè)置整體樣式,緊跟坐標(biāo)參數(shù)之后,是c
、marker
、linestyle
三個(gè)參數(shù)的整合,用于快速設(shè)置,也可選擇單獨(dú)設(shè)置這三個(gè)參數(shù);參數(shù)
c
設(shè)置線(xiàn)和標(biāo)記的顏色,只能是單個(gè)顏色,默認(rèn)'b'
藍(lán)色;參數(shù)
marker
設(shè)置標(biāo)記樣式,默認(rèn)None
;參數(shù)
linestyle
設(shè)置線(xiàn)條樣式,默認(rèn)'-'
實(shí)線(xiàn);參數(shù)
alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.
,值越小透明度越高;參數(shù)
linewidth
設(shè)置線(xiàn)的寬度;參數(shù)
markersize
設(shè)置標(biāo)記的大小。
3. 曲面圖
#曲面圖
n = 480
x = np.arange(n)
y = np.arange(n)
x,y = np.meshgrid(x,y)
z = np.cos(x*np.pi/180)+np.sin(y*np.pi/180)
fig=plt.figure()
ax=fig.add_subplot(111,title='3d surface',projection='3d')
ax.plot_surface(x,y,z,rstride=10,cstride=10,cmap=plt.cm.winter)
plt.show()
plot_surface
方法用于繪制曲面圖:參數(shù)
rstride
和cstride
設(shè)置x、y軸方向上的采樣步長(zhǎng),被采樣的數(shù)據(jù)才會(huì)用于曲面的繪制,值越小表示采樣精度越高,繪制的圖像越精細(xì),繪制時(shí)間也更長(zhǎng),與rcount
和ccount
參數(shù)不兼容;參數(shù)
rcount
和ccount
設(shè)置x、y軸方向上的采樣總數(shù),默認(rèn)50;參數(shù)
cmap
設(shè)置曲面顏色集,需要是colormap
,默認(rèn)藍(lán)色單色漸變;參數(shù)
alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.,值越小透明度越高。
繪制曲面圖需要構(gòu)造xy平面上的網(wǎng)格數(shù)據(jù)以及對(duì)應(yīng)的z值,可使用numpy的mgrid
索引器或meshgrid
方法實(shí)現(xiàn)。
4. 條形圖
x = np.array([1,2,3,4])
y1 = np.array([4,3,3,1])
y2 = np.array([2,5,1,3])
tick_label = ['a','b','c','d']
fig=plt.figure(figsize=(10,3))
ax=fig.add_subplot(131,title='2d bar')
ax.bar(x+0.15,y1,width=0.3,color='y',label='y1',alpha=0.7, tick_label=tick_label)
ax.bar(x-0.15,y2,width=0.3,color='g',label='y2',alpha=0.7, tick_label=tick_label)
ax.legend()
ax=fig.add_subplot(132,title='2d bar in 3d axes',projection='3d')
ax.bar(x,y1,0,'y',label='y1',edgecolor='k',linewidth=1)
ax.bar(x,y2,1,'y',label='y2',edgecolor='k',linewidth=1)
ax.legend(facecolor='none')
ax=fig.add_subplot(133,title='3d bar',projection='3d')
bar3d1=ax.bar3d(x,0,0,0.5,0.25,y1,label='y1')
bar3d2=ax.bar3d(x,1,0,0.5,0.25,y2,label='y2')
bar3d1._facecolors2d=bar3d1._facecolors3d
bar3d1._edgecolors2d=bar3d1._edgecolors3d
bar3d2._facecolors2d=bar3d2._facecolors3d
bar3d2._edgecolors2d=bar3d2._edgecolors3d
ax.legend()
plt.show()
bar
方法用于繪制條形圖(水平條形圖請(qǐng)使用barh
):
2D
第一個(gè)參數(shù)x
是條形的橫坐標(biāo),對(duì)齊的基準(zhǔn)由align
參數(shù)設(shè)置,默認(rèn)是與中心對(duì)齊;
第二個(gè)參數(shù)height
設(shè)置條形的高度;
第三個(gè)參數(shù)width
設(shè)置條形的寬度;
第四個(gè)參數(shù)bottom
設(shè)置條形底部的起始縱坐標(biāo),默認(rèn)0;
參數(shù)color
設(shè)置條形的顏色;
參數(shù)tick_label
設(shè)置橫坐標(biāo)刻度標(biāo)簽;
參數(shù)edge_color
和linewidth
設(shè)置邊緣線(xiàn)的顏色和粗細(xì);
參數(shù)label
設(shè)置此次繪制的類(lèi)別標(biāo)簽;
參數(shù)alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.,值越小透明度越高。
2d條形圖在繪制時(shí)視需要調(diào)整x的值,不然多次繪制的條形會(huì)重疊在一起。
2D in Axes3D
第一個(gè)參數(shù)left
設(shè)置條形的起始橫坐標(biāo),相當(dāng)于2d情況下設(shè)置align='edge'
;
第二個(gè)參數(shù)height
設(shè)置條形的高度,與2d情況下一樣;
第三個(gè)參數(shù)zs
設(shè)置z軸的取值;
第四個(gè)參數(shù)zdir
設(shè)置作為z軸的軸,默認(rèn)'z'
;
其余拓展參數(shù)和2d的一樣。
3D
第1,2,3個(gè)參數(shù)x
,y
,z
設(shè)置條形的位置坐標(biāo);
第4,5,6個(gè)參數(shù)dx
,dy
,dz
設(shè)置條形的長(zhǎng)寬高;
其余拓展參數(shù)和2d的一樣。
3D條形圖需要顯示圖例時(shí)必須為_facecolors2d
、_edgecolors2d
賦值,因?yàn)樯蓤D例使用的是2d的色彩設(shè)置,這應(yīng)該是一個(gè)bug。
5. 直方圖
x = np.random.randn(1000)
y = np.random.randn(1000)
fig=plt.figure(figsize=(9,3))
ax=fig.add_subplot(121,title='hist')
result1=ax.hist(x,bins=20,color="g",edgecolor="k",alpha=0.5,density=True)
ax=fig.add_subplot(122,title='hist2d')
result2=ax.hist2d(x,y,bins=20)
plt.show()
hist
方法用于繪制直方圖:第1個(gè)參數(shù)
x
設(shè)置需要統(tǒng)計(jì)的數(shù)據(jù),y
軸數(shù)據(jù)是統(tǒng)計(jì)頻次,自動(dòng)計(jì)算不需要自行設(shè)置;第2個(gè)參數(shù)
bins
設(shè)置分箱數(shù)量,即分成多少個(gè)等間隔的統(tǒng)計(jì)區(qū)間,默認(rèn)10;參數(shù)
color
或facecolor
設(shè)置條形的顏色;參數(shù)edgecolor
設(shè)置邊緣線(xiàn)的顏色;參數(shù)
density
設(shè)置是否歸一化,F(xiàn)alse時(shí)統(tǒng)計(jì)頻次,True時(shí)統(tǒng)計(jì)概率密度,默認(rèn)False;參數(shù)
alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.,值越小透明度越高。
hist2d
方法用于繪制二維直方圖:
第1,2個(gè)參數(shù)x
,y
設(shè)置需要統(tǒng)計(jì)的數(shù)據(jù),二維直方圖中統(tǒng)計(jì)頻次以顏色來(lái)體現(xiàn);
第3個(gè)參數(shù)bins
設(shè)置分箱數(shù)量,即分成多少個(gè)等間隔的統(tǒng)計(jì)區(qū)間,默認(rèn)10,x
,y
可以分別設(shè)置;
參數(shù)cmap
設(shè)置顏色集。
調(diào)用繪圖方法后會(huì)得到返回值:頻次和頻率的統(tǒng)計(jì)結(jié)果。
6. 餅圖/環(huán)圖
x1 = np.array([1,2,3,4])
x1_labels = ['a','b','c','d']
x1_explode = [0.2,0,0,0]
x2 = np.array([2,2,1,5])
fig=plt.figure(figsize=(9,4))
ax=fig.add_subplot(121,title='pie')
ax.pie(x1,explode=x1_explode,labels=x1_labels,shadow=True,autopct='%1.1f%%')
ax=fig.add_subplot(122,title='ring')
ax.pie(x1,radius=1,wedgeprops=dict(width=0.3, edgecolor='w'))
ax.pie(x2,radius=0.7,wedgeprops=dict(width=0.3, edgecolor='w'))
plt.show()
pie
方法用于繪制餅圖:
第一個(gè)參數(shù)x
設(shè)置每個(gè)扇形的比重,會(huì)自動(dòng)計(jì)算x/sum(x)應(yīng)用于繪制,但在sum(x)<1時(shí),不會(huì)進(jìn)行該計(jì)算;
第二個(gè)參數(shù)explode
設(shè)置每個(gè)扇形偏離中心的距離,默認(rèn)None;
第三個(gè)參數(shù)labels
設(shè)置每個(gè)扇形的標(biāo)簽;
第四個(gè)參數(shù)colors
設(shè)置顏色序列,繪制扇形時(shí)會(huì)輪流使用該序列中的顏色;
參數(shù)shadow
設(shè)置是否繪制陰影,默認(rèn)False;
參數(shù)labeldistance
設(shè)置扇形標(biāo)簽與中心的距離;
參數(shù)radius
設(shè)置扇形的半徑,默認(rèn)為1;
參數(shù)autopct
設(shè)置扇形上顯示的信息,可以是一個(gè)字符串格式或是一個(gè)函數(shù);
參數(shù)wedgeprops
設(shè)置扇形的樣式,其中width
是寬度,與radius
一致時(shí)繪制出來(lái)的就是餅圖,小于radius
則是環(huán)圖,edgecolor
和linewidth
可以設(shè)置邊緣線(xiàn)的顏色和寬度;
參數(shù)center
設(shè)置餅圖的中心,默認(rèn)(0,0)。
7. 箱線(xiàn)圖
def test_data():
spread = np.random.rand(50)
center = np.ones(25) * 0.5
flier_high = np.random.rand(10)+1
flier_low = np.random.rand(10)-1
return np.r_[spread,center,flier_high,flier_low]
x1 = test_data()
x2 = test_data()
fig=plt.figure()
ax=fig.add_subplot(111,title='box')
ax.boxplot([x1,x2],labels=['x1','x2'],widths=0.3)
plt.show()
boxplot
方法用于繪制箱線(xiàn)圖:第一個(gè)參數(shù)
x
設(shè)置用于繪圖的數(shù)據(jù),當(dāng)有多組時(shí)可以放在一個(gè)list中傳入;參數(shù)
labels
設(shè)置每組數(shù)據(jù)的類(lèi)別標(biāo)簽;參數(shù)
width
設(shè)置圖形的寬度。
8. 等高線(xiàn)圖
x = np.arange(-3,3,0.01)
y = np.arange(-3,3,0.01)
x,y = np.meshgrid(x,y)
z = (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)+1
fig=plt.figure(figsize=(13.5,3))
ax=fig.add_subplot(131,title='2d contourf')
c=ax.contour(x,y,z,colors='k',linewidths=0.5)
ax.clabel(c,fontsize=10)
cf=ax.contourf(x,y,z,cmap='YlOrRd')
cbar=fig.colorbar(cf)
ax=fig.add_subplot(132,title='3d contourf',projection='3d')
ax.contourf(x,y,z,cmap='YlOrRd')
ax.contour(x,y,z,colors='k',linewidths=0.2)
ax=fig.add_subplot(133,title='3d surface with contour',projection='3d')
ax.plot_surface(x,y,z,cmap='YlOrRd',alpha=0.7)
ax.contour(x,y,z,colors='k',linewidths=1)
plt.show()
contour
方法用于繪制等高線(xiàn)圖:
第1,2,3個(gè)參數(shù)x
,y
,z
設(shè)置用于繪圖的數(shù)據(jù),z
是高度;
第4個(gè)參數(shù)levels
設(shè)置等高線(xiàn)的數(shù)量;
參數(shù)colors
設(shè)置等高線(xiàn)使用的顏色序列;
參數(shù)linewidths
設(shè)置等高線(xiàn)的寬度序列;
參數(shù)linestyles
設(shè)置等高線(xiàn)的樣式序列。
contourf
方法用于填充等高線(xiàn)圖:
第1,2,3個(gè)參數(shù)x
,y
,z
設(shè)置用于繪圖的數(shù)據(jù),z
是高度;
第4個(gè)參數(shù)levels
設(shè)置等高線(xiàn)的數(shù)量;
參數(shù)cmap
設(shè)置用于填充的顏色集;
參數(shù)alpha
設(shè)置點(diǎn)的透明度,默認(rèn)1.,值越小透明度越高。
clabel
方法用于設(shè)置等高線(xiàn)標(biāo)簽;
colorbar
方法用于設(shè)置參考顏色條;
9. 極坐標(biāo)圖
theta=np.linspace(0,2*np.pi,100)
fig=plt.figure(figsize=(10,5))
ax=fig.add_subplot(121,title='polar1',projection='polar')
ax.plot(theta,theta,c='b',lw=2)
ax.set_rmax(theta.max())
ax=fig.add_subplot(122,title='polar2',projection='polar')
ax.plot(theta,theta,c='r',lw=2)
ax.set_rmax(theta.max())
ax.set_rlabel_position(90)
ax.set_theta_offset(np.pi)
ax.set_thetagrids(np.arange(0,360,15))
ax.set_rticks(np.arange(0,6.5,0.5))
ax.set_theta_direction(-1)
通過(guò)設(shè)置projection='polar'
創(chuàng)建PolarAxes
坐標(biāo)軸,即可實(shí)現(xiàn)極坐標(biāo)作圖:
set_rmax
,set_rmin
,set_rlim
方法分別可以設(shè)置極徑的最大值,最小值,以及范圍;
set_rlabel_position
方法設(shè)置極徑標(biāo)簽的位置,以角度表示;
set_theta_offset
方法設(shè)置角度的偏移量,以弧度表示;
set_thetagrids
方法設(shè)置角度刻度序列,會(huì)影響網(wǎng)格線(xiàn);
set_rticks
方法設(shè)置極徑刻度序列,會(huì)影響網(wǎng)格線(xiàn);
set_theta_direction
方法設(shè)置角度增長(zhǎng)方向。
在調(diào)用plot
等方法繪圖時(shí),原本的x
和y
分別對(duì)應(yīng)到角度和極徑。
四. 其他繪圖元素
1. 注解annotate
fig=plt.figure(figsize=(10,3.5))
ax=fig.add_subplot(121,title='annotate')
ax.scatter([-0.25],[-0.25],s=100)
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
bbox_style = dict(boxstyle="square", fc='white', ec='black',lw=1)
arrow_style = dict(arrowstyle='->',color='black',lw=2)
ax.annotate('This is a dot.',(-0.24,-0.24),(-0.14,0.16),
arrowprops=arrow_style,bbox=bbox_style,fontsize=15)
ax=fig.add_subplot(122,title='arrow+text')
ax.scatter([-0.25],[-0.25],s=100)
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.arrow(0.09,0.06,-0.25,-0.23,fc='k',ec='k',
width=0.01,head_width=0.07,head_length=0.07)
ax.text(-0.14,0.16,'This is a dot.',fontsize=15,bbox=bbox_style)
annotate
方法用于向圖像上添加注解:第一個(gè)參數(shù)
s
設(shè)置注釋的文本;第二個(gè)參數(shù)
xy
設(shè)置要注釋的點(diǎn)位置,tuple
類(lèi)型表示的坐標(biāo);第三個(gè)參數(shù)
xytext
設(shè)置注釋文本的位置,tuple
類(lèi)型表示的坐標(biāo);參數(shù)
xycoords
和textcoords
設(shè)置注釋點(diǎn)位置和文本位置所采用的坐標(biāo)系,默認(rèn)'data'
和數(shù)據(jù)的坐標(biāo)系一致;參數(shù)
arrowprops
設(shè)置箭頭,dict
類(lèi)型,其中arrowstyle
屬性設(shè)置樣式,color
屬性設(shè)置顏色,lw
屬性設(shè)置箭頭寬度;以上三個(gè)參數(shù)具體信息建議參考官方文檔-annotate;
參數(shù)
bbox
設(shè)置文本框樣式,dict
類(lèi)型,其中boxstyle
屬性設(shè)置樣式,fc
屬性設(shè)置填充顏色,ec
屬性設(shè)置邊緣顏色,lw
屬性設(shè)置邊緣線(xiàn)寬度;bbox
中的詳細(xì)設(shè)置建議參考官方文檔-Rectangle;參數(shù)
fontsize
設(shè)置字體大小。
注解也可通過(guò)arrow
+text
實(shí)現(xiàn)。
arrow
方法用于添加箭頭:
第1,2個(gè)參數(shù)x
,y
設(shè)置箭頭的起始位置;
第3,4個(gè)參數(shù)dx
,dy
設(shè)置箭頭往xy方向延伸的長(zhǎng)度;
fc
參數(shù)設(shè)置填充顏色;ec
參數(shù)設(shè)置邊緣顏色;
width
參數(shù)設(shè)置箭頭線(xiàn)寬度;
head_width
參數(shù)設(shè)置箭頭頭部的寬度;
head_length
參數(shù)設(shè)置箭頭頭部的長(zhǎng)度。
text
方法用于添加文本:
第1,2個(gè)參數(shù)x
,y
設(shè)置文本的位置;
第3個(gè)參數(shù)s
設(shè)置要顯示的文本;
參數(shù)fontsize
設(shè)置字體大小;
參數(shù)bbox
設(shè)置文本框樣式,與annotate
相同。
arrow
繪制的箭頭在有所傾斜時(shí)無(wú)法保證頭部的底部與線(xiàn)垂直,對(duì)此有要求只能使用annotate
。
2. 區(qū)域填充fill
x=np.arange(0,720,1)
y1=np.sin(x*np.pi/180)
y2=np.cos(x*np.pi/180)
fig=plt.figure(figsize=(10,3.5))
ax=fig.add_subplot(121,title='fill')
ax.plot(x,y1)
ax.plot(x,y2)
ax.fill(x,y1,color='g',alpha=0.3)
ax.fill(x,y2,color='b',alpha=0.3)
ax=fig.add_subplot(122,title='fill between')
ax.plot(x,y1)
ax.plot(x,y2)
ax.fill_between(x,y1,y2,color='g',alpha=0.3)
fill
方法用于填充多邊形:第1,2個(gè)參數(shù)
x
,y
設(shè)置邊的xy坐標(biāo),該繪圖方法不適合填充不封閉的曲線(xiàn),會(huì)如上圖出現(xiàn)無(wú)法預(yù)估的繪制效果。
fill_between
方法用于填充兩條曲線(xiàn)中間的區(qū)域:
第1,2,3個(gè)參數(shù)x
,y1
,y2
設(shè)置x坐標(biāo)和兩條曲線(xiàn)的y坐標(biāo);
第4個(gè)參數(shù)where
設(shè)置繪制的橫坐標(biāo)范圍,布爾數(shù)組類(lèi)型,相當(dāng)于對(duì)前三個(gè)參數(shù)執(zhí)行索引篩選。
3. 圖片image
from PIL import Image
image1=Image.open('D:\\training_data\\used\\cifar-10-batches-py\\test\\1_貓.png')
image2=Image.open('D:\\training_data\\used\\cifar-10-batches-py\\test\\2_船.png')
fig=plt.figure(figsize=(8,4))
ax=fig.add_subplot(121,title='image1')
ax.imshow(image1)
ax=fig.add_subplot(122,title='image2')
ax.imshow(image2)
imshow
用于顯示圖片,默認(rèn)是會(huì)顯示坐標(biāo)軸和刻度的,可通過(guò)Axes.axis('off')
關(guān)閉。
4. 基本圖形patch
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
fig=plt.figure(figsize=(9,3))
ax=fig.add_subplot(121,title='Rectangle')
rects=[]
x=[1.5,3.5,5.5,]
y=[3,4.5,3]
for i in range(3):
rect=patches.Rectangle((x[i],y[i]),3,3)
rects.append(rect)
pc=PatchCollection(rects,linewidth=1,edgecolor='r',facecolor='none')
#ax.add_patch(rect)
ax.add_collection(pc)
ax.set_xlim([0,10])
ax.set_ylim([0,10])
ax=fig.add_subplot(122,title='Ellipse')
ells=[]
for i in range(5):
ell=patches.Ellipse((5,5),6,3,angle=i*36)
ells.append(ell)
pc=PatchCollection(ells,facecolor='g',alpha=0.5)
#ax.add_patch(ell)
ax.add_collection(pc)
ax.set_xlim([0,10])
ax.set_ylim([0,10])
繪制基本圖形和相應(yīng)集合需要導(dǎo)入
patches
和PatchCollection
。
patches
提供了各種圖形的構(gòu)造:
Rectangle
是矩形類(lèi),第1個(gè)參數(shù)xy
設(shè)置左下角頂點(diǎn)的坐標(biāo),第2,3個(gè)參數(shù)width
,height
設(shè)置寬度和高度,第4個(gè)參數(shù)angle
設(shè)置旋轉(zhuǎn)角度;
Ellipse
是橢圓類(lèi),第1個(gè)參數(shù)xy
設(shè)置橢圓中心的坐標(biāo),第2,3個(gè)參數(shù)width
,height
設(shè)置橫軸和豎軸的長(zhǎng)度(直徑),第4個(gè)參數(shù)angle
設(shè)置旋轉(zhuǎn)角度。
PatchCollection
用于構(gòu)造patches
集合并設(shè)置通用的拓展參數(shù):
linewidth
參數(shù)設(shè)置邊緣線(xiàn)寬;
edgecolor
參數(shù)設(shè)置邊緣顏色;
facecolor
參數(shù)設(shè)置填充顏色,facecolor='none'
可以設(shè)置不填充(在創(chuàng)建圖形類(lèi)時(shí),fill=False
也能設(shè)置不填充);
alpha
參數(shù)設(shè)置透明度。
add_patch
用于向Axes
中添加單個(gè)圖形;
add_collection
用于向Axes
中添加圖形集合;
Axes.patches
可以查看Axes
下的所有Patch
繪圖對(duì)象;
Axes.collections
可以查看Axes
下的所有繪圖集合。
5. 數(shù)據(jù)表格table
data=np.array([[1,2,3],[4,5,6],[7,8,9]])
row_labels=['row1','row2','row3']
row_colors=plt.cm.BuPu(np.linspace(0, 0.5, len(row_labels)))
col_labels=['col1','col2','col3']
col_index=np.arange(3)
fig=plt.figure()
ax=fig.add_subplot(111,title='table')
for i in range(len(row_labels)-1,-1,-1):
ax.bar(col_index,data[i],color=row_colors[i],linewidth=0.5,edgecolor='k')
ax.table(cellText=data,
rowLabels=row_labels,
rowColours=row_colors,
colLabels=col_labels,
loc='bottom')
ax.set_xticks([])
table
方法用于添加表格:
cellText
參數(shù)設(shè)置單元格數(shù)據(jù),二維序列類(lèi)型,默認(rèn)None
;
cellColors
參數(shù)設(shè)置單元格顏色,二維序列類(lèi)型,默認(rèn)None
;
cellText
和cellColors
兩個(gè)參數(shù)至少有一個(gè)要賦值;
cellLoc
參數(shù)設(shè)置單元格位置,默認(rèn)'right'
;
colWidths
參數(shù)設(shè)置列寬,一維序列類(lèi)型,可選;
rowLabels
參數(shù)設(shè)置行標(biāo)簽,一維序列類(lèi)型,可選;
rowColors
參數(shù)設(shè)置行標(biāo)簽顏色,一維序列類(lèi)型,可選;
rowLoc
參數(shù)設(shè)置行標(biāo)簽位置,默認(rèn)'left'
;
colLabels
參數(shù)設(shè)置列標(biāo)簽,一維序列類(lèi)型,可選;
colColors
參數(shù)設(shè)置列標(biāo)簽顏色,一維序列類(lèi)型,可選;
colLoc
參數(shù)設(shè)置列標(biāo)簽位置,默認(rèn)'center'
;
loc
參數(shù)設(shè)置表格位置,默認(rèn)bottom
;
bbox
參數(shù)設(shè)置方框樣式,可選。
更詳細(xì)的設(shè)置可以自行創(chuàng)建Table
對(duì)象,通過(guò)Axes.add_table
方法添加;
Axes.tables
可以查看Axes
下的所有Table
繪圖對(duì)象。