1. 程式人生 > >Matplotlib.pyplot 常用方法(一)

Matplotlib.pyplot 常用方法(一)

簡介

matplotlib是python上的一個2D繪相簿,它可以在誇平臺上邊出很多高質量的影象。綜旨就是讓簡單的事變得更簡單,讓複雜的事變得可能。我們可以用matplotlib生成 繪圖、直方圖、功率譜、柱狀圖、誤差圖、散點圖等 。

matplotlib.pyplot:提供一個類似matlab的繪圖框架。

pylab將pyplot與numpy合併為一個名稱空間。這對於互動式工作很方便,但是對於程式設計來說,建議將名稱空間分開,例如 :

# 畫 y = sin x 影象
import numpy as np
import matplotlib.pyplot as plt

x = np.arange
(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) plt.show()

matplotlib實際上為面向物件的繪相簿,它所繪製的每個元素都有一個物件與之對應的。例如上述例子中執行完 plt.plot(x,y) 之後得到:[matplotlib.lines.Line2D object at 0x01867D70]

好啦,現在開始學習:

配置屬性:

因為是面向物件的繪相簿,我們可以為每個物件配置它們的屬性,應該說有三個方法,一個是通過物件的方法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')

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

Artist 物件

對於上面的很多很多物件,其實都是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('time')           # 用axes物件的set_xlabel函式來設定它的xlabel

line =ax.plot(range(5))[0]      # 用axes物件的plot()進行繪圖,它返回一個Line2D的物件;
line.set_color('r')             # 再呼叫Line2D的物件的set_color函式設定color的屬性;
plt.show()

輸出 為:

這裡寫圖片描述

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 物件列表,用於顯示文字;
# 使用figure物件繪製直線
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt

fig = plt.figure()

line1 = Line2D([0,1],[0,1], transform=fig.transFigure, figure=fig, color="r")
line2 = Line2D([0,1],[1,0], transform=fig.transFigure, figure=fig, color="b")
fig.lines.extend([line1, line2])

fig.show()

執行結果:
這裡寫圖片描述

axes 容器

它是整個matplotlib的核心,它包含了組成圖表的眾多的artist物件。並且有很多方法。我們常用的Line2D啦,Xaxis,YAxis等都是它的屬性哦;可以通過這個物件的屬性來設定座標軸的label啦,範圍啦等之類的。乾脆直接用plt.getp()檢視它的屬性,然後通過set_屬性名()函式來設定就好啦。

axis 容器

axis容器包括了座標軸上的刻度線、刻度標籤等、座標網路等內容。

對於座標軸上的刻度相關的知識,它是這麼分的:首先是major_ticks()和minor_ticks(), 然後呢,每個刻度又包括刻度線(ticklines)、刻度標籤(ticklabels)、刻度位置(ticklocs)。本來呢,axis應該刻度,然後呢,刻度再包含那三個,但是呢,為了方便,axis就都包含了。其實也是有點交叉吧。上面的axes也會交叉包含它所包含物件的物件的。

看個例子:

from matplotlib.lines import Line2D
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('red')          # 設定每個刻度標籤的顏色;
    label.set_rotation(45)          # 旋轉45度;
    label.set_fontsize(16)          # 設定字型大小;
for line in axis.get_ticklines():
    line.set_color('green')          
    line.set_markersize(15)         # 設定刻度線的長短;
    line.set_markeredgewidth(3)     # 設定線的粗細
plt.show()

執行結果:
這裡寫圖片描述

pyplot函式提供了兩個繪製文字的函式:text()和figtext()。它們分別呼叫了當前的Axes物件與當前的Figure物件的text()方法進行繪製文字。text()預設在數字座標系(就是axes在的座標系,用座標軸的數字來表示座標)中畫, figtext()預設在圖表座標系(就是figure在圖表中啦,座標範圍從0 到 1 )中畫,我們可能通過trransform引數進行座標系的轉換。反正吧,matplotlib中一共有四種座標系,並且可以轉換的哦,提一下哈。

簡單的呼叫:

plt.text(1, 1, ‘hello,world’, color = ‘bule’) #還可以寫更多引數的;
plt.figtexe(0.1, 0.8 ,”i am in figure’, color = ‘green’)

上面說了一大堆了,現在說幾個常用的畫圖函式吧:

常用函式

plot()

可以畫出很簡單線圖,基本用法:

plot(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 matplotlib.pyplot as plt
import numpy as np  

plt.figure(1)                   # 呼叫figure函式建立figure(1)物件,可以省略,這樣那plot時,它就自動建一個啦;

t = np.arange(0.0, 2.0, 0.1)
s = np.sin(2*np.pi*t)
plt.plot(t, s, 'r--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, axis_bgcolor = color)
plt.show()

這裡寫圖片描述

利用subplot_adjust()函式可以對畫的多個子圖進行調整,優化間隔,它一共有left、right, bottom, top, wspace, hspase 六個引數,取 值從0至1。

"""
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt


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, 'r.-')
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()
figure_1

這裡寫圖片描述

twinx()或twiny()

twinx():在同一圖畫中,共享x軸,但是擁有各自不同的y軸

create a twin of Axes for generating a plot with a sharex
x-axis but independent y axis. The y-axis of self will have
ticks on left and the returned axes will have ticks on the
right.

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()  

執行結果:
這裡寫圖片描述