Python--matplotlib繪圖可視化知識點整理

from:https://segmentfault.com/a/1190000005104723html

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

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

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

參考

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圖標正常顯示中文

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

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

這種方法可以奏效的條件是電腦上有simhei字體。數組

matplotlib inline和pylab inline

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

%matplotlib inline #notebook模式下 %pylab inline #ipython模式下

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

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

爲項目設置matplotlib參數

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

  • 使用參數字典(rcParams)

  • 調用matplotlib.rc()命令 經過傳入關鍵字元祖,修改參數

若是不想每次使用matplotlib時都在代碼部分進行配置,能夠修改matplotlib的文件參數。能夠用以下命令來找到當前用戶的配置文件目錄。

import matplotlib matplotlib.get_data_path()

獲得配置文件夾,其中有font文件夾。

配置文件包括如下配置項:

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

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:

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

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, ifautopct='%.2f', then for each pie wedge, the format string is '%.2f' and the numerical percent valuefor that wedge is pct, so the wedge label is set to the string '%.2f'%pct.

  1. DataHub-Python 數據可視化入門1 
  2. Matplotlib 教程 
  3. 繪圖: matplotlib核心剖析 
  4. python如何調整子圖的大小? 
相關文章
相關標籤/搜索