matplotlib.pyplot是一個有命令風格的函數集合,它看起來和MATLAB很相似。每一個pyplot函數都使一副圖像做出些許改變,例如創建一幅圖,在圖中創建一個繪圖區域,在繪圖區域中添加一條線等等。在matplotlib.pyplot中,各種狀態通過函數調用保存起來,以便於可以隨時跟蹤像當前圖像和繪圖區域這樣的東西。繪圖函數是直接作用於當前axes(matplotlib中的專有名詞,圖形中組成部分,不是數學中的座標系。)
舉一個簡單的例子:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
- 1
- 2
- 3
- 4
運行結果
你可能會很疑惑X和Y軸爲什麼是0~3和1~4。原因是這樣的,這裏我們只是爲plot()命令提供 了一個list或者是array,matplotlib就會假設這個序列是Y軸上的取值,並且會自動爲你生成X軸上的值。因爲python中的範圍是從0開始的,因此X軸就是從0開始,長度與Y的長度相同,也就是[0,1,2,3]。
plot()是一個靈活的命令,它的參數可以是任意數量,比如:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
- 1
這表示的是(x,y)對,(1,1)(2,4)(3,9)(4,16)。這裏有第三個可選參數,它是字符串格式的,表示顏色和線的類型。該字符串格式中的字母和符號來自於MATLAB,它是顏色字符串和線的類型字符串的組合。默認情況下,該字符串參數是’b-‘,表示藍色的實線。
舉一個使用紅色圓圈繪製上述點集的例子:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
- 1
- 2
- 3
- 4
可以查看plot()的文檔,那裏有完整的關於線的類型的說明。axis()命令可以方便的獲取和設置XY軸的一些屬性。
如果matplotlib僅限於使用上面那種list,那麼它將顯得毫無用處。通常,我們都是使用numpy數組,實際上,所有的序列都將被在內部被轉化成numpy數字。下面的例子是使用一個命令用幾種不同風格的線繪製一個數組:
import numpy as np
import matplotlib.pyplot as plt
# 0到5之間每隔0.2取一個數
t = np.arange(0., 5., 0.2)
# 紅色的破折號,藍色的方塊,綠色的三角形
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
控制線的屬性
線有許多屬性可以設置:線寬、線的形狀,平滑等等。這裏有一些設置線屬性的方法:
- 使用關鍵字參數
plt.plot(x,y,linewidth=2.0)
- 1
- 對線對象(Line2D)使用set_方法,plot()會返回一個線對象的列表,比如line1, line2 = plot(x1, y1, x2, y2)。下面的代碼我們將假設我們只有一條線,即返回的線對象列表的長度爲1。
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # 關閉平滑
- 1
- 2
- 使用setp()命令。 下面的例子使用的是MATLAB風格的命令去設置一個線的列表的多個屬性。setp()可以作用於一個列表對象或者是一個單一的對象。你可以使用python風格的關鍵字參數或者是MATLAB風格的string/value對爲參數:
lines = plt.plot(x1, y1, x2, y2)
# 使用關鍵字
plt.setp(lines, color='r', linewidth=2.0)
# 或者是MATLAB風格的string/value對
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
這是一些Line2D的屬性和取值:
工作在多圖形(figures)和多座標系(axes)
MATLAB和pyplot都有當前圖形(figure)和當前座標系(axes)的概念。所有的繪圖命令都是應用於當前座標系的。gca()和gcf()(get current axes/figures)分別獲取當前axes和figures的對象。通常,你不用擔心這些,因爲他們都在幕後被保存了,下面是一個例子,創建了兩個子繪圖區域(subplot):
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure("2subplot")
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
figure()命令在這兒可以不寫,因爲figure(1)將會被默認執行,同樣,subplot(111)也是默認被執行的。subplot()中的參數分別指定了numrows、numcols、fignum,其中fignum的取值範圍爲1到numrows*numcols,分別表示的是將繪圖區域劃分爲numrows行和numcols列個子繪圖區域,fignum爲當前子圖的編號。編號是從1開始,一行一行由左向右編號的。其實subplot中的參數【111】本應寫作【1,1,1】,但是如果這三個參數都小於10(其實就是第三個參數小於10)就可以省略逗號。你可以創建任意數量的子圖(subplots)和座標系(axes)。如果你想手動放置一個axes,也就是它不再是一個矩形方格,你就可以使用命令axes(),它可以讓座標系位於任何位置,axes([left,bottom,width,height]),其中所有的值都是0到1(axes([0.3,0.4,0.2,0.3])表示的是該座標系位於figure的(0.3,0.4)處,其寬度和長度分別爲figure橫座標和縱座標總長的0.2和0.3)。其實subplot和axes的區別就在於axes大小和位置更加隨意。
你可以創建多個figure,通過調用figure(),其參數爲figure的編號。當然每個figure可以包含多個subplot或者是多個axes。例子:
import matplotlib.pyplot as plt
plt.figure(1) # 編號爲1的figure
plt.subplot(211) # figure1中的第一個子圖
plt.plot([1, 2, 3])
plt.subplot(212) # figure1中的第二個子圖
plt.plot([4, 5, 6])
plt.figure(2) # figure2
plt.plot([4, 5, 6]) # 默認使用subplot(111),此時figure2爲當
# 前figure
plt.figure(1) # 設置figure1爲當前figure;
# 但是subplot(212)爲當前子圖
plt.subplot(211) # 使subplot(211)爲當前子圖
plt.title('Easy as 1, 2, 3') # 對subplot(211)命名
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
我們可以使用clf()和cla()(clear current figure/axes)清除當前figure和當前axes。
如果你創建了許多figures,你需要注意一件事:figure的內存直到顯示調用close()函數纔會被完全釋放,否則它並沒有被全部釋放。如果只是刪掉對figure的引用,或者是通過關閉window進程管理器關閉該figure,這都是不完全刪除figure的,因爲pyplot在內部維持了一個引用,直到close()被調用。
文字
text()命令可以被用來在任何位置添加文字,xlabel()、ylabel()、title()被用來在指定位置添加文字。
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# 直方圖
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
所有text()命令返回一個matplotlib.text.Text實例,像上面的線一樣,可以通過關鍵字參數在text()定製文本樣式,也可以通過setp()來定製文字的樣式:
t = plt.xlabel('my data', fontsize=14, color='red')
setp(t,color='blue')
- 1
- 2
- 在文本中使用數學表達式
matplotlib接受任何TeX方程表達式,比如,你可以寫成用”$”符號包裹的TeX表達式:
plt.title(r'$\sigma_i=15$')
- 1
這裏的”r”非常重要,它表示後面的字符串是一個純粹的字符串,不會將後面的反斜槓當作轉義字符。matplotlib內置有TeX表達式解釋器和排版引擎,和自帶的數學字體。因此你可以不用安裝TeX就能使用數學表達式,如果你安裝了LaTeX和dvipng,你也可以使用LaTex排版你的文字並且直接輸出到figures或者是保存。
- 註釋文本
使用text()命令可以在Axes中任意位置放置文本,一個普遍的文本用法是對一些特性進行註釋,annotate()方法讓添加註釋變得很容易。對於註釋有兩點需要注意:需要被註釋的地方,使用xy參數來指出,還有就是註釋文本所放置的位置,使用參數xytext來指定位置,這兩個參數都使(x,y)元組:
import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
這裏的xy和xytext所使用的座標是根據XY軸的刻度的座標,稱爲data coordinates。當然也可以使用其他座標系統,具體參考官方文檔。
對數和其他非線性座標軸(axis)
matplotlib.pylot不僅僅提供了線性的座標,還提供了對數(logarithmic)和分對數(logit)座標。當數據的維度跨越許多數量級時,這種座標就很有用,改變座標軸的刻度很容易:
plt.xscale(‘log’)
- 1
下面是一個例子,對於同樣的數據,在Y軸使用不同刻度下的曲線圖:
import numpy as np
import matplotlib.pyplot as plt
# 在區間[0,1]製造一些數據
# np.random.normal爲高斯分佈
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# 創建一個窗口
plt.figure(1)
# 線性
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# 對數
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
我們也可以添加自己的刻度和投影。具體這裏先不介紹,後續會深入講解更多matplotlib的用法。
作者也是邊學邊寫博客,有諸多不對之處敬請諒解。
參考文檔:Pyplot tutorial
注:轉載請註明原文出處:
作者:CUG_UESTC
出處:http://blog.csdn.net/qq_31192383/article/details/53977822