python_matplotlib知識點總結

文做爲學習過程當中對matplotlib一些經常使用知識點的整理,方便查找。html

強烈推薦ipython
不管你工做在什麼項目上,IPython都是值得推薦的。利用ipython --pylab,能夠進入PyLab模式,已經導入了matplotlib庫與相關軟件包(例如Numpy和Scipy),額能夠直接使用相關庫的功能。python

這樣IPython配置爲使用你所指定的matplotlib GUI後端(TK/wxPython/PyQt/Mac OS X native/GTK)。對於大部分用戶而言,默認的後端就已經夠用了。Pylab模式還會向IPython引入一大堆模塊和函數以提供一種更接近MATLAB的界面。後端

參考

 

 

[python]  view plain  copy
 
  1. import matplotlib.pyplot as plt  
  2. labels='frogs','hogs','dogs','logs'  
  3. sizes=15,20,45,10  
  4. colors='yellowgreen','gold','lightskyblue','lightcoral'  
  5. explode=0,0.1,0,0  
  6. plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)  
  7. plt.axis('equal')  
  8. plt.show()  



 

matplotlib圖標正常顯示中文

爲了在圖表中可以顯示中文和負號等,須要下面一段設置:dom

 

 

[python]  view plain  copy
 
  1. import matplotlib mpl  
  2. mpl.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤  
  3. mpl.rcParams['axes.unicode_minus']=False #用來正常顯示負號  



 

matplotlib inline和pylab inline

可使用ipython --pylab打開ipython命名窗口。函數

 

 

[plain]  view plain  copy
 
  1. %matplotlib inline #notebook模式下  
  2. %pylab inline #ipython模式下  



 

這兩個命令均可以在繪圖時,將圖片內嵌在交互窗口,而不是彈出一個圖片窗口,可是,有一個缺陷:除非將代碼一次執行,不然,沒法疊加繪圖,由於在這兩種模式下,是要有plt出現,圖片會立馬show出來,所以:學習

推薦在ipython notebook時使用,這樣就能很方便的一次編輯完代碼,繪圖。字體

 

爲項目設置matplotlib參數

在代碼執行過程當中,有兩種方式更改參數:this

  • 使用參數字典(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()。

[python]  view plain  copy
 
  1. plt.tilte('Title in a custom color',color='#123456')  



 

背景色

經過向如matplotlib.pyplot.axes()或者matplotlib.pyplot.subplot()這樣的方法提供一個axisbg參數,能夠指定座標這的背景色。

 

[python]  view plain  copy
 
  1. 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座標範圍

 

 

[python]  view plain  copy
 
  1. %matplotlib inline  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4. from pylab import *  
  5. x = np.arange(-5.0, 5.0, 0.02)  
  6. y1 = np.sin(x)  
  7. plt.figure(1)  
  8. plt.subplot(211)  
  9. plt.plot(x, y1)  
  10. plt.subplot(212)  
  11. #設置x軸範圍  
  12. xlim(-2.5, 2.5)  
  13. #設置y軸範圍  
  14. ylim(-1, 1)  
  15. plt.plot(x, y1)  



 

 

疊加圖

用一條指令畫多條不一樣格式的線。

 

 

[python]  view plain  copy
 
  1. import numpy as np  
  2. import matplotlib.pyplot as plt  
  3. # evenly sampled time at 200ms intervals  
  4. t = np.arange(0., 5., 0.2)  
  5. # red dashes, blue squares and green triangles  
  6. plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')  
  7. plt.show()  



 

 

plt.figure()

你能夠屢次使用figure命令來產生多個圖,其中,圖片號按順序增長。這裏,要注意一個概念當前圖和當前座標。全部繪圖操做僅對當前圖和當前座標有效。一般,你並不須要考慮這些事,下面的這個例子爲你們演示這一細節。

 

 

[python]  view plain  copy
 
  1. import matplotlib.pyplot as plt  
  2. plt.figure(1) # 第一張圖  
  3. plt.subplot(211) # 第一張圖中的第一張子圖  
  4. plt.plot([1,2,3])  
  5. plt.subplot(212) # 第一張圖中的第二張子圖  
  6. plt.plot([4,5,6])  
  7. plt.figure(2) # 第二張圖  
  8. plt.plot([4,5,6]) # 默認建立子圖subplot(111)  
  9. plt.figure(1) # 切換到figure 1 ; 子圖subplot(212)仍舊是當前圖  
  10. plt.subplot(211) # 令子圖subplot(211)成爲figure1的當前圖  
  11. plt.title('Easy as 1,2,3') # 添加subplot 211 的標題  



 

figure感受就是給圖像ID,以後能夠索引定位到它。

 

plt.text()添加文字說明

  • text()能夠在圖中的任意位置添加文字,並支持LaTex語法

  • xlable(), ylable()用於添加x軸和y軸標籤

  • title()用於添加圖的題目

 

 

[python]  view plain  copy
 
  1. import numpy as np  
  2. import matplotlib.pyplot as plt  
  3. mu, sigma = 100, 15  
  4. x = mu + sigma * np.random.randn(10000)  
  5. # 數據的直方圖  
  6. n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)  
  7. plt.xlabel('Smarts')  
  8. plt.ylabel('Probability')  
  9. #添加標題  
  10. plt.title('Histogram of IQ')  
  11. #添加文字  
  12. plt.text(60, .025, r'$\mu=100,\ \sigma=15$')  
  13. plt.axis([40, 160, 0, 0.03])  
  14. plt.grid(True)  
  15. plt.show()  



 


text中前兩個參數感受應該是文本出現的座標位置。

 

plt.annotate()文本註釋

在數據可視化的過程當中,圖片中的文字常常被用來註釋圖中的一些特徵。使用annotate()方法能夠很方便地添加此類註釋。在使用annotate時,要考慮兩個點的座標:被註釋的地方xy(x, y)和插入文本的地方xytext(x, y)。1

 

 

[python]  view plain  copy
 
  1. import numpy as np  
  2. import matplotlib.pyplot as plt  
  3. ax = plt.subplot(111)  
  4. t = np.arange(0.0, 5.0, 0.01)  
  5. s = np.cos(2*np.pi*t)  
  6. line, = plt.plot(t, s, lw=2)  
  7. plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),  
  8. arrowprops=dict(facecolor='black', shrink=0.05),  
  9. )  
  10. plt.ylim(-2,2)  
  11. plt.show()  



 

 

plt.xticks()/plt.yticks()設置軸記號

如今是明白乾嗎用的了,就是人爲設置座標軸的刻度顯示的值。

 

 

[python]  view plain  copy
 
  1. # 導入 matplotlib 的全部內容(nympy 能夠用 np 這個名字來使用)  
  2. from pylab import *  
  3. # 建立一個 8 * 6 點(point)的圖,並設置分辨率爲 80  
  4. figure(figsize=(8,6), dpi=80)  
  5. # 建立一個新的 1 * 1 的子圖,接下來的圖樣繪製在其中的第 1 塊(也是惟一的一塊)  
  6. subplot(1,1,1)  
  7. X = np.linspace(-np.pi, np.pi, 256,endpoint=True)  
  8. C,S = np.cos(X), np.sin(X)  
  9. # 繪製餘弦曲線,使用藍色的、連續的、寬度爲 1 (像素)的線條  
  10. plot(X, C, color="blue", linewidth=1.0, linestyle="-")  
  11. # 繪製正弦曲線,使用綠色的、連續的、寬度爲 1 (像素)的線條  
  12. plot(X, S, color="r", lw=4.0, linestyle="-")  
  13. plt.axis([-4,4,-1.2,1.2])  
  14. # 設置軸記號  
  15. xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],  
  16. [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])  
  17. yticks([-1, 0, +1],  
  18. [r'$-1$', r'$0$', r'$+1$'])  
  19. # 在屏幕上顯示  
  20. show()  



 


當咱們設置記號的時候,咱們能夠同時設置記號的標籤。注意這裏使用了 LaTeX。2

 

移動脊柱 座標系

 

 

[python]  view plain  copy
 
  1. ax = gca()  
  2. ax.spines['right'].set_color('none')  
  3. ax.spines['top'].set_color('none')  
  4. ax.xaxis.set_ticks_position('bottom')  
  5. ax.spines['bottom'].set_position(('data',0))  
  6. ax.yaxis.set_ticks_position('left')  
  7. ax.spines['left'].set_position(('data',0))  



 

這個地方確實沒看懂,囧,之後再說吧,感受就是移動了座標軸的位置。

 

plt.legend()添加圖例

 

 

[python]  view plain  copy
 
  1. plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")  
  2. plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")  
  3. legend(loc='upper left')  



 

 

matplotlib.pyplot

使用plt.style.use('ggplot')命令,能夠做出ggplot風格的圖片。

 

 

[python]  view plain  copy
 
  1. # Import necessary packages  
  2. import pandas as pd  
  3. %matplotlib inline  
  4. import matplotlib.pyplot as plt  
  5. plt.style.use('ggplot')  
  6. from sklearn import datasets  
  7. from sklearn import linear_model  
  8. import numpy as np  
  9. # Load data  
  10. boston = datasets.load_boston()  
  11. yb = boston.target.reshape(-1, 1)  
  12. Xb = boston['data'][:,5].reshape(-1, 1)  
  13. # Plot data  
  14. plt.scatter(Xb,yb)  
  15. plt.ylabel('value of house /1000 ($)')  
  16. plt.xlabel('number of rooms')  
  17. # Create linear regression object  
  18. regr = linear_model.LinearRegression()  
  19. # Train the model using the training sets  
  20. regr.fit( Xb, yb)  
  21. # Plot outputs  
  22. plt.scatter(Xb, yb, color='black')  
  23. plt.plot(Xb, regr.predict(Xb), color='blue',  
  24. linewidth=3)  
  25. plt.show()  



 

 

給特殊點作註釋

好吧,又是註釋,多個例子參考一下!

咱們但願在 2π/32π/3 的位置給兩條函數曲線加上一個註釋。首先,咱們在對應的函數圖像位置上畫一個點;而後,向橫軸引一條垂線,以虛線標記;最後,寫上標籤。

 

 

[python]  view plain  copy
 
  1. t = 2*np.pi/3  
  2. # 做一條垂直於x軸的線段,由數學知識可知,橫座標一致的兩個點就在垂直於座標軸的直線上了。這兩個點是起始點。  
  3. plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")  
  4. scatter([t,],[np.cos(t),], 50, color ='blue')  
  5. annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',  
  6. xy=(t, np.sin(t)), xycoords='data',  
  7. xytext=(+10, +30), textcoords='offset points', fontsize=16,  
  8. arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))  
  9. plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")  
  10. scatter([t,],[np.sin(t),], 50, color ='red')  
  11. annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',  
  12. xy=(t, np.cos(t)), xycoords='data',  
  13. xytext=(-90, -50), textcoords='offset points', fontsize=16,  
  14. 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

plt.axes-官方文檔

  • 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:

 

 

[python]  view plain  copy
 
  1. http://matplotlib.org/examples/pylab_examples/axes_demo.html  
  2. import matplotlib.pyplot as plt  
  3. import numpy as np  
  4. # 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()  
  5. dt = 0.001  
  6. t = np.arange(0.0, 10.0, dt)  
  7. r = np.exp(-t[:1000]/0.05) # impulse response  
  8. x = np.random.randn(len(t))  
  9. s = np.convolve(x, r)[:len(x)]*dt # colored noise  
  10. # the main axes is subplot(111) by default  
  11. plt.plot(t, s)  
  12. plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])  
  13. plt.xlabel('time (s)')  
  14. plt.ylabel('current (nA)')  
  15. plt.title('Gaussian colored noise')  
  16. # this is an inset axes over the main axes  
  17. a = plt.axes([.65, .6, .2, .2], axisbg='y')  
  18. n, bins, patches = plt.hist(s, 400, normed=1)  
  19. plt.title('Probability')  
  20. plt.xticks([])  
  21. plt.yticks([])  
  22. # this is another inset axes over the main axes  
  23. a = plt.axes([0.2, 0.6, .2, .2], axisbg='y')  
  24. plt.plot(t[:len(r)], r)  
  25. plt.title('Impulse response')  
  26. plt.xlim(0, 0.2)  
  27. plt.xticks([])  
  28. plt.yticks([])  
  29. plt.show()  



 

pyplot.pie參數

colors顏色

找出matpltlib.pyplot.plot中的colors能夠取哪些值?

 

 

[python]  view plain  copy
 
  1. for name,hex in matplotlib.colors.cnames.iteritems():  
  2.   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.
相關文章
相關標籤/搜索