Pyplot教程(深度學習入門3)

源地址:http://matplotlib.org/users/pyplot_tutorial.htmljavascript

 

 

Pyplot tutorial

 

matplotlib.pyplot是一組命令函數集合,使得matplotlib.pyplot像matlab同樣工做。每一個pyplot函數能夠對圖片作一些操做,好比:建立圖片,在圖片中建立繪圖區域,在繪圖區域中畫一些線,在所繪的圖上添加屬性等等。在matplotlib.pyplot中,pyplot經過函數調用保存各個狀態,以便跟蹤如當前圖形或繪圖區域的內容。css

In [2]:
import matplotlib.pyplot as plt
import numpy as np
In [3]:
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
 
 

讀者也許會感到奇怪,爲何繪製一個從1-4的列表,會給出一個二維的顯示。當繪製一個一維列表或序列時,plot函數會認爲這是y軸的值加以顯示,x軸的值自動生成。因爲python從0開始,而給出的數據是1-4共計4個數字,因此x軸的數據是0-3一樣也是4個數字.html

 

plot()是一組通用命令,能夠接受任意的參數,也能夠同時接受x與y,例如:plt.plot([1, 2, 3, 4], [1, 4, 9, 16])html5

 

plot()有第三個可選參數,便可以選擇線形以及顏色。全部用於表示顏色和形狀的字符源於MATLAB,默認的字符爲‘b-’(若是用過matlab確定知道)。舉例來講:java

In [4]:
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
 
 

上面例子中的axis()中的list參數表示[xmin, xmax, ymin, ymax],同時能夠指定軸的可視範圍。python

 

通常狀況下,咱們使用numpy提供的數組。事實上,全部的數組都須要內部轉換爲numpy提供的數組。下面的例子採用一條語句實現不一樣風格的線。jquery

# evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show()
 

線的屬性

 

能夠設置的線屬性主要包含有:線寬、虛實等等。線屬性的設置方法有以下幾種:linux

 

1.使用關鍵字參數:plt.plot(x, y, linewidth=2.0)android

 

2.使用Line2D實例,plot返回Line2D對象,例如:line1, line2 = plot(x1, y1, x2, y2)。css3

line, = plt.plot(x, y, '-') line.set_antialiased(False) # turn off antialising
 

3.得到線屬性,使用setp()函數設置

lines = plt.plot(x1, y1, x2, y2) #use keyword args plt.setp(lines, color='r', linewidth=2.0) #or MATLAB style string value pairs plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
 

Line2D屬性的詳細屬性見:http://matplotlib.org/users/pyplot_tutorial.html

 

操做多線條與多圖片

 

Matlab與pyplot針對當前圖片或當前軸進行操做,gca()返回當前座標軸,gcf()返回當前的圖片。通常狀況下,不用理會這兩個操做,下面的操做幫你完成你的任務

In [19]:
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(1)
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()
 
 

figure()操做是可選操做,系統默認建立的圖像爲figure 1。subplot的默認操做爲subplot(111)。

 

你能夠經過屢次調用figure()函數。

In [22]:
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
plt.show()
 
 
 

text()命令可用於在任意位置添加文本,並使用xlabel(),ylabel()和title()在指定位置添加文本

In [23]:
# Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
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()
 
 

全部的text()命令返回 matplotlib.text.Text實例。經過傳遞關鍵詞參數到text(),屬性能夠被定製。好比:t = plt.xlabel('my data', fontsize=14, color='red')

在圖片中使用數學表達式:plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
 

annotate()方法能夠很方便的提供註解功能,在註釋函數中,有兩點須要注意:1.註解箭頭須要添加的位置,用xy表示,以及註解內容的位置,用xytext表示。添加註解:

In [25]:
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()
 
 

對數以及其餘非線性表示

 

matplotlib.pyplot不只支持線性,還支持對數和對數。 若是數據跨越許多數量級,這是經常使用的方法。 更改很容易:

In [26]:
from matplotlib.ticker import NullFormatter

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
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))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
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.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()
 
In [ ]:
相關文章
相關標籤/搜索