文作為學習過程中對matplotlib一些常用知識點的整理,方便查找。
強烈推薦ipython
無論你工作在什么項目上,IPython都是值得推薦的。利用ipython --pylab
,可以進入PyLab模式,已經導入了matplotlib庫與相關軟件包(例如Numpy和Scipy),額可以直接使用相關庫的功能。
這樣IPython配置為使用你所指定的matplotlib GUI后端(TK/wxPython/PyQt/Mac OS X native/GTK)。對於大部分用戶而言,默認的后端就已經夠用了。Pylab模式還會向IPython引入一大堆模塊和函數以提供一種更接近MATLAB的界面。
參考
- import matplotlib.pyplot as plt
- labels='frogs','hogs','dogs','logs'
- sizes=15,20,45,10
- colors='yellowgreen','gold','lightskyblue','lightcoral'
- explode=0,0.1,0,0
- plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)
- plt.axis('equal')
- plt.show()
matplotlib圖標正常顯示中文
為了在圖表中能夠顯示中文和負號等,需要下面一段設置:
- import matplotlib mpl
- mpl.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽
- mpl.rcParams['axes.unicode_minus']=False #用來正常顯示負號
matplotlib inline和pylab inline
可以使用ipython --pylab
打開ipython命名窗口。
- %matplotlib inline #notebook模式下
- %pylab inline #ipython模式下
這兩個命令都可以在繪圖時,將圖片內嵌在交互窗口,而不是彈出一個圖片窗口,但是,有一個缺陷:除非將代碼一次執行,否則,無法疊加繪圖,因為在這兩種模式下,是要有plt
出現,圖片會立馬show
出來,因此:
推薦在ipython notebook時使用,這樣就能很方便的一次編輯完代碼,繪圖。
為項目設置matplotlib參數
在代碼執行過程中,有兩種方式更改參數:
-
使用參數字典(rcParams)
-
調用matplotlib.rc()命令 通過傳入關鍵字元祖,修改參數
如果不想每次使用matplotlib時都在代碼部分進行配置,可以修改matplotlib的文件參數。可以用matplot.get_config()
命令來找到當前用戶的配置文件目錄。
配置文件包括以下配置項:
axex: 設置坐標軸邊界和表面的顏色、坐標刻度值大小和網格的顯示
backend: 設置目標暑促TkAgg和GTKAgg
figure: 控制dpi、邊界顏色、圖形大小、和子區( subplot)設置
font: 字體集(font family)、字體大小和樣式設置
grid: 設置網格顏色和線性
legend: 設置圖例和其中的文本的顯示
line: 設置線條(顏色、線型、寬度等)和標記
patch: 是填充2D空間的圖形對象,如多邊形和圓。控制線寬、顏色和抗鋸齒設置等。
savefig: 可以對保存的圖形進行單獨設置。例如,設置渲染的文件的背景為白色。
verbose: 設置matplotlib在執行期間信息輸出,如silent、helpful、debug和debug-annoying。
xticks和yticks: 為x,y軸的主刻度和次刻度設置顏色、大小、方向,以及標簽大小。
線條相關屬性標記設置
用來該表線條的屬性
線條風格linestyle或ls | 描述 | 線條風格linestyle或ls | 描述 | |
---|---|---|---|---|
'-' | 實線 | ':' | 虛線 | |
'--' | 破折線 | 'None',' ','' | 什么都不畫 | |
'-.' | 點划線 |
線條標記
標記maker | 描述 | 標記 | 描述 | |
---|---|---|---|---|
'o' | 圓圈 | '.' | 點 | |
'D' | 菱形 | 's' | 正方形 | |
'h' | 六邊形1 | '*' | 星號 | |
'H' | 六邊形2 | 'd' | 小菱形 | |
'_' | 水平線 | 'v' | 一角朝下的三角形 | |
'8' | 八邊形 | '<' | 一角朝左的三角形 | |
'p' | 五邊形 | '>' | 一角朝右的三角形 | |
',' | 像素 | '^' | 一角朝上的三角形 | |
'+' | 加號 | '\ | ' | 豎線 |
'None','',' ' | 無 | 'x' | X |
顏色
可以通過調用matplotlib.pyplot.colors()
得到matplotlib支持的所有顏色。
別名 | 顏色 | 別名 | 顏色 | |
---|---|---|---|---|
b | 藍色 | g | 綠色 | |
r | 紅色 | y | 黃色 | |
c | 青色 | k | 黑色 | |
m | 洋紅色 | w | 白色 |
如果這兩種顏色不夠用,還可以通過兩種其他方式來定義顏色值:
-
使用HTML十六進制字符串
color='eeefff'
使用合法的HTML顏色名字('red','chartreuse'等)。 -
也可以傳入一個歸一化到[0,1]的RGB元祖。
color=(0.3,0.3,0.4)
很多方法可以介紹顏色參數,如title()。
- plt.tilte('Title in a custom color',color='#123456')
背景色
通過向如matplotlib.pyplot.axes()
或者matplotlib.pyplot.subplot()
這樣的方法提供一個axisbg
參數,可以指定坐標這的背景色。
- subplot(111,axisbg=(0.1843,0.3098,0.3098)
基礎
如果你向plot()指令提供了一維的數組或列表,那么matplotlib將默認它是一系列的y值,並自動為你生成x的值。默認的x向量從0開始並且具有和y同樣的長度,因此x的數據是[0,1,2,3].
圖片來自:繪圖: matplotlib核心剖析
確定坐標范圍
-
plt.axis([xmin, xmax, ymin, ymax])
上面例子里的axis()命令給定了坐標范圍。 -
xlim(xmin, xmax)和ylim(ymin, ymax)來調整x,y坐標范圍
- %matplotlib inline
- import numpy as np
- import matplotlib.pyplot as plt
- from pylab import *
- x = np.arange(-5.0, 5.0, 0.02)
- y1 = np.sin(x)
- plt.figure(1)
- plt.subplot(211)
- plt.plot(x, y1)
- plt.subplot(212)
- #設置x軸范圍
- xlim(-2.5, 2.5)
- #設置y軸范圍
- ylim(-1, 1)
- plt.plot(x, y1)
疊加圖
用一條指令畫多條不同格式的線。
- import numpy as np
- import matplotlib.pyplot as plt
- # 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()
plt.figure()
你可以多次使用figure命令來產生多個圖,其中,圖片號按順序增加。這里,要注意一個概念當前圖和當前坐標。所有繪圖操作僅對當前圖和當前坐標有效。通常,你並不需要考慮這些事,下面的這個例子為大家演示這一細節。
- import matplotlib.pyplot as plt
- plt.figure(1) # 第一張圖
- plt.subplot(211) # 第一張圖中的第一張子圖
- plt.plot([1,2,3])
- plt.subplot(212) # 第一張圖中的第二張子圖
- plt.plot([4,5,6])
- plt.figure(2) # 第二張圖
- plt.plot([4,5,6]) # 默認創建子圖subplot(111)
- plt.figure(1) # 切換到figure 1 ; 子圖subplot(212)仍舊是當前圖
- plt.subplot(211) # 令子圖subplot(211)成為figure1的當前圖
- plt.title('Easy as 1,2,3') # 添加subplot 211 的標題
figure感覺就是給圖像ID,之后可以索引定位到它。
plt.text()添加文字說明
-
text()可以在圖中的任意位置添加文字,並支持LaTex語法
-
xlable(), ylable()用於添加x軸和y軸標簽
-
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()
text中前兩個參數感覺應該是文本出現的坐標位置。
plt.annotate()文本注釋
在數據可視化的過程中,圖片中的文字經常被用來注釋圖中的一些特征。使用annotate()方法可以很方便地添加此類注釋。在使用annotate時,要考慮兩個點的坐標:被注釋的地方xy(x, y)和插入文本的地方xytext(x, y)。1
- 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()
plt.xticks()/plt.yticks()設置軸記號
現在是明白干嘛用的了,就是人為設置坐標軸的刻度顯示的值。
- # 導入 matplotlib 的所有內容(nympy 可以用 np 這個名字來使用)
- from pylab import *
- # 創建一個 8 * 6 點(point)的圖,並設置分辨率為 80
- figure(figsize=(8,6), dpi=80)
- # 創建一個新的 1 * 1 的子圖,接下來的圖樣繪制在其中的第 1 塊(也是唯一的一塊)
- subplot(1,1,1)
- X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
- C,S = np.cos(X), np.sin(X)
- # 繪制余弦曲線,使用藍色的、連續的、寬度為 1 (像素)的線條
- plot(X, C, color="blue", linewidth=1.0, linestyle="-")
- # 繪制正弦曲線,使用綠色的、連續的、寬度為 1 (像素)的線條
- plot(X, S, color="r", lw=4.0, linestyle="-")
- plt.axis([-4,4,-1.2,1.2])
- # 設置軸記號
- xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
- [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
- yticks([-1, 0, +1],
- [r'$-1$', r'$0$', r'$+1$'])
- # 在屏幕上顯示
- show()
當我們設置記號的時候,我們可以同時設置記號的標簽。注意這里使用了 LaTeX。2
移動脊柱 坐標系
- ax = gca()
- ax.spines['right'].set_color('none')
- ax.spines['top'].set_color('none')
- ax.xaxis.set_ticks_position('bottom')
- ax.spines['bottom'].set_position(('data',0))
- ax.yaxis.set_ticks_position('left')
- ax.spines['left'].set_position(('data',0))
這個地方確實沒看懂,囧,以后再說吧,感覺就是移動了坐標軸的位置。
plt.legend()添加圖例
- plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
- plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
- legend(loc='upper left')
matplotlib.pyplot
使用plt.style.use('ggplot')
命令,可以作出ggplot風格的圖片。
- # Import necessary packages
- import pandas as pd
- %matplotlib inline
- import matplotlib.pyplot as plt
- plt.style.use('ggplot')
- from sklearn import datasets
- from sklearn import linear_model
- import numpy as np
- # Load data
- boston = datasets.load_boston()
- yb = boston.target.reshape(-1, 1)
- Xb = boston['data'][:,5].reshape(-1, 1)
- # Plot data
- plt.scatter(Xb,yb)
- plt.ylabel('value of house /1000 ($)')
- plt.xlabel('number of rooms')
- # Create linear regression object
- regr = linear_model.LinearRegression()
- # Train the model using the training sets
- regr.fit( Xb, yb)
- # Plot outputs
- plt.scatter(Xb, yb, color='black')
- plt.plot(Xb, regr.predict(Xb), color='blue',
- linewidth=3)
- plt.show()
給特殊點做注釋
好吧,又是注釋,多個例子參考一下!
我們希望在 2π/32π/3 的位置給兩條函數曲線加上一個注釋。首先,我們在對應的函數圖像位置上畫一個點;然后,向橫軸引一條垂線,以虛線標記;最后,寫上標簽。
- t = 2*np.pi/3
- # 作一條垂直於x軸的線段,由數學知識可知,橫坐標一致的兩個點就在垂直於坐標軸的直線上了。這兩個點是起始點。
- plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
- scatter([t,],[np.cos(t),], 50, color ='blue')
- annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
- xy=(t, np.sin(t)), xycoords='data',
- xytext=(+10, +30), textcoords='offset points', fontsize=16,
- arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
- plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
- scatter([t,],[np.sin(t),], 50, color ='red')
- annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
- xy=(t, np.cos(t)), xycoords='data',
- xytext=(-90, -50), textcoords='offset points', fontsize=16,
- arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.subplot()
plt.subplot(2,3,1)
表示把圖標分割成2*3的網格。也可以簡寫plt.subplot(231)
。其中,第一個參數是行數,第二個參數是列數,第三個參數表示圖形的標號。
plt.axes()
我們先來看什么是Figure和Axes對象。在matplotlib中,整個圖像為一個Figure對象。在Figure對象中可以包含一個,或者多個Axes對象。每個Axes對象都是一個擁有自己坐標系統的繪圖區域。其邏輯關系如下34:
-
axes() by itself creates a default full subplot(111) window axis.
-
axes(rect, axisbg='w') where rect = [left, bottom, width, height] in normalized (0, 1) units. axisbg is the background color for the axis, default white.
-
axes(h) where h is an axes instance makes h the current axis. An Axes instance is returned.
rect=[左, 下, 寬, 高] 規定的矩形區域,rect矩形簡寫,這里的數值都是以figure大小為比例,因此,若是要兩個axes並排顯示,那么axes[2]的左=axes[1].左+axes[1].寬,這樣axes[2]才不會和axes[1]重疊。
show code:
- http://matplotlib.org/examples/pylab_examples/axes_demo.html
- import matplotlib.pyplot as plt
- import numpy as np
- # create some data to use for the plot dt = 0.001 t = np.arange(0.0, 10.0, dt) r = np.exp(-t[:1000]/0.05) # impulse response x = np.random.randn(len(t)) s = np.convolve(x, r)[:len(x)]*dt # colored noise # the main axes is subplot(111) by default plt.plot(t, s) plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)]) plt.xlabel('time (s)') plt.ylabel('current (nA)') plt.title('Gaussian colored noise') # this is an inset axes over the main axes a = plt.axes([.65, .6, .2, .2], axisbg='y') n, bins, patches = plt.hist(s, 400, normed=1) plt.title('Probability') plt.xticks([]) plt.yticks([]) # this is another inset axes over the main axes a = plt.axes([0.2, 0.6, .2, .2], axisbg='y') plt.plot(t[:len(r)], r) plt.title('Impulse response') plt.xlim(0, 0.2) plt.xticks([]) plt.yticks([]) plt.show()
- dt = 0.001
- t = np.arange(0.0, 10.0, dt)
- r = np.exp(-t[:1000]/0.05) # impulse response
- x = np.random.randn(len(t))
- s = np.convolve(x, r)[:len(x)]*dt # colored noise
- # the main axes is subplot(111) by default
- plt.plot(t, s)
- plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
- plt.xlabel('time (s)')
- plt.ylabel('current (nA)')
- plt.title('Gaussian colored noise')
- # this is an inset axes over the main axes
- a = plt.axes([.65, .6, .2, .2], axisbg='y')
- n, bins, patches = plt.hist(s, 400, normed=1)
- plt.title('Probability')
- plt.xticks([])
- plt.yticks([])
- # this is another inset axes over the main axes
- a = plt.axes([0.2, 0.6, .2, .2], axisbg='y')
- plt.plot(t[:len(r)], r)
- plt.title('Impulse response')
- plt.xlim(0, 0.2)
- plt.xticks([])
- plt.yticks([])
- plt.show()
pyplot.pie參數
colors顏色
找出matpltlib.pyplot.plot中的colors可以取哪些值?
- for name,hex in matplotlib.colors.cnames.iteritems():
- print name,hex
打印顏色值和對應的RGB值。
-
plt.axis('equal')
避免比例壓縮為橢圓
autopct
autopct enables you to display the percent value using Python string formatting. For example, if autopct='%.2f', then for each pie wedge, the format string is '%.2f' and the numerical percent value for that wedge is pct, so the wedge label is set to the string '%.2f'%pct.