1、介紹
Matplotlib 是一個 Python 的 2D繪圖庫,它以各種硬拷貝格式和跨平台的交互式環境生成出版質量級別的圖形。通過 Matplotlib,開發者可以僅需要幾行代碼,便可以生成繪圖,
直方圖,功率譜,條形圖,錯誤圖,散點圖等。
2、Matplotlib基礎知識
2.1、Matplotlib中的基本圖表包括的元素
2.2、hold屬性
2.3、網格線
2.4、axis方法
2.5、xlim方法和ylim方法
3、配置屬性
Matplotlib.plt是面向對象的繪圖庫,可以為每個對象配置它們的屬性,有三個方法:
- 對象的set_屬性名()
- 對象的set()
- pylot模塊提供的setp()函數
如下例子:
plt.figure() line = plt.plot(range(5))[0] # plot函數返回的是一個列表,因為可以同時畫多條線的哦; line.set_color('r') line.set_linewidth(2.0) plt.show() #################################### plt.figure() line = plt.plot(range(5))[0] # plot函數返回的是一個列表,因為可以同時畫多條線; line.set(color = 'g',linewidth = 2.0) plt.show() #################################### plt.figure() lines = plt.plot(range(5),range(5),range(5),range(8,13)) # plot函數返回一個列表; plt.setp(lines, color = 'g',linewidth = 2.0) # setp函數可以對多條線進行設置的; plt.show()
獲取屬性:
- 一個是通過對象的方法get_屬性名()函數,
- 一個是通過pylot模塊提供的getp()函數。
getp()有兩個調用方法,一個是只有要的查看的對象一個參數,一個是要查看的對象現屬性兩個參數;如:
# getp(obj, property=None) plt.getp(line) plt.getp(line, 'color')
4、Artist 對象
matplotlib API包含有三層:
- backend_bases.FigureCanvas : 圖表的繪制領域
- backend_bases.Renderer : 知道如何在FigureCanvas上如何繪圖
- artist.Artist : 知道如何使用Renderer在FigureCanvas上繪圖
FigureCanvas和Renderer需要處理底層的繪圖操作,例如使用wxPython在界面上繪圖,或者使用PostScript繪制PDF。Artist則處理所有的高層結構,例如處理圖表、
文字和曲線等的繪制和布局。通常我們只和Artist打交道,而不需要關心底層的繪制細節。
Artists分為簡單類型和容器類型兩種。簡單類型的Artists為標准的繪圖元件,例如Line2D、 Rectangle、 Text、AxesImage 等等。而容器類型則可以包含許多簡單類型的Artists,
使它們組織成一個整體,例如Axis、 Axes、Figure等。
直接使用Artists創建圖表的標准流程如下:
創建Figure對象
用Figure對象創建一個或者多個Axes或者Subplot對象
調用Axies等對象的方法創建各種簡單類型的Artists
4.1、Artist 對象
Artist對象共分為簡單類型和容器類型兩種哦。
下面是一個簡單Artist對象的創建過程:
import matplotlib.pyplot as plt import numpy as np fig = plt.figure(1) # 創建了一個figure對象; # figure對象的add_axes()可以在其中創建一個axes對象, # add_axes()的參數為一個形如[left, bottom, width, height]的列表,取值范圍在0與1之間; # 我們把它放在了figure圖形的上半部分,對應參數分別為:left, bottom, width, height; ax = fig.add_axes([0.1, 0.5, 0.8, 0.5]) ax.set_xlabel('x') # 用axes對象的set_xlabel函數來設置它的xlabel ax.set_ylabel('y') line =ax.plot(range(5))[0] # 用axes對象的plot()進行繪圖,它返回一個Line2D的對象; line.set_color('g') # 再調用Line2D的對象的set_color函數設置color的屬性; plt.show()
輸出圖形:
5、figure 容器
在構成圖表的各種Artist對象中,最上層的Artist對象是Figure。我們可以調用add_subplot()與add_axes()方法向圖表中添加子圖,它們分加到figure的axes的屬性列表中。
add_subplot()與add_axes()返回新創建的axes對象,分別為axesSuubplot與axes, axesSuubplot為 axes的派生類。另外,可以通過delaxes()方法來刪除哦;
figure對象可以有自己的簡單的artist對象。
下面列出Figure對象中包含的其他Artist對象的屬性:
axes:Axes對象列表;
patch:作為背景的Rectangle對象;
images:FigureImage對象列表,用於顯示圖像;
legends:Legend 對象列表,用於顯示圖示;
lines:Line2D對象列表;
patches:Patch對象列表;
texts:Text 對象列表,用於顯示文字;
6、axes 容器
它是整個matplotlib的核心,它包含了組成圖表的眾多的artist對象。並且有很多方法。我們常用的Line2D啦,Xaxis,YAxis等都是它的屬性哦;可以通過這個對象的屬性來設置坐標軸的label,
范圍啦等之類的。干脆直接用plt.getp()查看它的屬性,然后通過set_屬性名()函數來設置就好啦。
7、axis 容器
axis容器包括了坐標軸上的刻度線、刻度標簽等、坐標網絡等內容。
坐標軸上的每個刻度包括刻度線(ticklines)、刻度標簽(ticklabels)、刻度位置(ticklocs)。
例子:
import numpy as np import matplotlib.pyplot as plt # 通過axis來更改坐標軸 plt.plot([1,2,3],[4,5,6]) # gca()獲取當前的axes繪圖區域,調用gcf()來獲得當前的figure axis = plt.gca().xaxis axis.get_ticklocs() # 得到刻度位置; axis.get_ticklabels() # 得到刻度標簽; axis.get_ticklines() # 得到刻度線; axis.get_ticklines(minor = True) # 得到次刻度線; 舉個例子:就像我們的尺子上的厘米的為主刻度線,毫米的為次刻度線; for label in axis.get_ticklabels(): label.set_color('blue') # 設置每個刻度標簽的顏色; label.set_rotation(90) # 旋轉45度; label.set_fontsize(16) # 設置字體大小; for line in axis.get_ticklines(): line.set_color('green') line.set_markersize(3) # 設置刻度線的長短; line.set_markeredgewidth(2) # 設置線的粗細 plt.show()
運行結果:
pyplot函數提供了兩個繪制文字的函數:text()和figtext()。它們分別調用了當前的Axes對象與當前的Figure對象的text()方法進行繪制文字。
text()默認在數字坐標系(就是axes在的坐標系,用坐標軸的數字來表示坐標)中畫, figtext()默認在圖表坐標系(就是figure在圖表中,坐標范圍從0 到 1 )中畫,
簡單的調用:
plt.text(1, 1, ‘hello,world’, color = ‘bule’) #還可以寫更多參數的;
plt.figtexe(0.1, 0.8 ,”i am in figure’, color = ‘green’)
8、常用函數
plot()
可以畫出很簡單線圖,基本用法:
lot(x, y) # 畫出橫軸為x與縱軸為y的圖,使用默認的線形與顏色;
plot(x, y, 'bo') # 用藍色,且點的標記用小圓,下面會解釋哦
plot(y) # 縱軸用y ,橫軸用y的每個元素的坐標,即0,1,2……
plot(y, 'r+') # 如果其中x或y 為2D的,則會用它的相應的每列來表示(注意是每列)
plot(x1, y1, 'g^', x2, y2, 'g-') #可以使用多對的x, y, format 對當作變量的,把它們畫一個圖里;
對於參數中,常用的format:線的顏色、線的形狀、點的標記形狀,我們用這三個的時候經常用縮寫,它們之間的順序怎么都可以,
如它倆一個意思:’r+–’、’+–r’。如果我們不想縮寫的話,可以分別寫成如: color=’green’, linestyle=’dashed’, marker=’o’。
線的形狀:
‘-’ solid line style
‘–’ dashed line style
‘-.’ dash-dot line style
‘:’ dotted line style
點的標記:
‘.’ point marker
‘,’ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
‘^’ triangle_up marker
‘<’ triangle_left marker
‘>’ triangle_right marker
‘1’ tri_down marker
‘2’ tri_up marker
‘3’ tri_left marker
‘4’ tri_right marker
‘s’ square marker
‘p’ pentagon marker
‘*’ star marker
‘h’ hexagon1 marker
‘H’ hexagon2 marker
‘+’ plus marker
‘x’ x marker
‘D’ diamond marker
‘d’ thin_diamond marker
‘|’ vline marker
‘_’ hline marker
線的顏色:
‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white
常見線的屬性有:color,labor,linewidth,linestyle,maker,等,參考:lines–matplotlib。
顯示正弦曲線
import numpy as np import matplotlib.pyplot as plt plt.figure('正弦曲線') # 調用figure函數創建figure(1)對象,可以省略,這樣那plot時,它就自動建一個啦; t = np.arange(0.0, 4.0, 0.1) s = np.sin(np.pi*t) plt.plot(t, s, 'g--o', label = 'sinx') plt.legend() # 顯示右上角的那個label,即上面的label = 'sinx' plt.xlabel('time (s)') # 設置x軸的label,pyplot模塊提供了很直接的方法,內部也是調用的上面當然講述的面向對象的方式來設置; plt.ylabel('voltage (mV)') # 設置y軸的label; #plt.xlim(-1,3) # 可以自己設置x軸的坐標的范圍哦; #plt.ylim(-1.5,1.5) plt.title('About as simple as it gets, folks') plt.grid(True) # 顯示網格; plt.show()
輸出圖形:
subplot()
利用subplot()函數可以返回一個axes的對象,函數為:subplot(numRows, numCols, plotnum),當這三個參數都小於10時,可以把它們寫一起,如下所示:
# 填充彩色子圖 import matplotlib.pyplot as plt import numpy as np for i, color in enumerate('rgbyck'): plt.subplot(321+i, facecolor = color) plt.show()
輸出圖形:
利用subplot_adjust()函數可以對畫的多個子圖進行調整,優化間隔,它一共有left、right, bottom, top, wspace, hspase 六個參數,取 值從0至1。
# 填充彩色子圖 import matplotlib.pyplot as plt import numpy as np x1 = np.linspace(0.0, 5.0) #生成一個一維的array,linspace(起始點,結束點,點數(默認為50)) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 2, 1) #表示在subplot為2*1的樣式,並在第一個子圖上畫出; plt.plot(x1, y1, 'yo-') plt.title('A tale of 2 subplots') plt.ylabel('Damped oscillation') plt.subplot(2, 2, 2) # 我們在第二個子圖上加個空圖哈,去理解它的圖的排序(即注意第二個子圖的位置 # 為第一行第二列)是按行優先的,這個正好和matlab里相反哦; plt.title('It is a empty figure') plt.subplot(2, 2, 4) plt.plot(x2, y2, 'g.-') plt.xlabel('time (s)') plt.ylabel('Undamped') plt.show()
輸出圖形:
subplots()
plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, **fig_kw)
作用:創建一個已有subplots的figures;
參數:
nrows : int ,指創建的sublots的行數,默認為1.
ncols : int ,指創建的sublots的列數,默認為1.
sharex : 為一個string或bool類型; 當為Ture時,所有的subpots將要共享x軸,如果它們是上下的關系的話,上面的圖的刻度label就沒有,只有下面那個圖的.
If a string must be one of "row", "col", "all", or "none". "all" has the same effect as *True*, "none" has the same effect as *False*. If "row", each subplot row will share a X axis. If "col", each subplot column will share a X axis and the x tick labels on all but the last row will have visible set to *False*. *sharey* : 同上 *squeeze* : bool 它是用來控制返回值的,根據返回的axis的結果決定要不要把沒有的維度進行壓縮一下. 當為Ture時,如果返回的axis只有一個,則表示成標量,如果有一行或一列,則表示為一維數組,如果多行多列,則表示為2D數組; 當為False時,不管多少個返回的axis,都以二維數組的方式返回; *subplot_kw* : dict Dict with keywords passed to the :meth:`~matplotlib.figure.Figure.add_subplot` call used to create each subplots. *fig_kw* : dict Dict with keywords passed to the :func:`figure` call. Note that all keywords not recognized above will be automatically included here.
返回值
有兩個fig和 axt(它是元組的方式)
*fig* is the :class:matplotlib.figure.Figure object
*ax * can be either a single axis object or an array of axis objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.
# subplots() 返回值 import matplotlib.pyplot as plt import numpy as np x = range(0,30,1) y = np.sin(x) # 接收返回的兩個對象 f,(ax1, ax2) = plt.subplots(1, 2, sharey=True) # 兩個對象分別畫圖 ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) plt.show()
輸出圖形:
twinx()或twiny()
twinx():在同一圖畫中,共享x軸,但是擁有各自不同的y軸
twiny():和上面一樣,不同之處在於,它共享y軸。
# twinx() 共享x軸實例 import matplotlib.pyplot as plt import numpy as np fig = plt.figure(1) ax1 =plt.subplot(111) ax2 = ax1.twinx() ax1.plot(np.arange(1,5),'g--') ax1.set_ylabel('ax1',color = 'r') ax2.plot(np.arange(7,10),'b-') ax2.set_ylabel('ax2',color = 'b') plt.show()
輸出圖形:
參考文章:
matplotlib.pyplot 官方文檔
博客園——matplotlib 常用知識
博客園——matplotlib 繪圖入門
matplotlib-繪制精美的圖表(Figure容器,Artist對象,Axes容器)
博客園——Matplotlib 詳解圖像各個部分
Matplotlib.pyplot 常用方法(一)