Python matplotlib繪圖可視化知識點整理(小結),pythonmatplotlib

來源:互聯網
上載者:User

Python matplotlib繪圖可視化知識點整理(小結),pythonmatplotlib

無論你工作在什麼項目上,IPython都是值得推薦的。利用ipython --pylab,可以進入PyLab模式,已經匯入了matplotlib庫與相關軟體包(例如Numpy和Scipy),額可以直接使用相關庫的功能。

本文作為學習過程中對matplotlib一些常用知識點的整理,方便尋找。

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

import matplotlib.pyplot as pltlabels='frogs','hogs','dogs','logs'sizes=15,20,45,10colors='yellowgreen','gold','lightskyblue','lightcoral'explode=0,0.1,0,0plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)plt.axis('equal')plt.show()

matplotlib表徵圖正常顯示中文

為了在圖表中能夠顯示中文和負號等,需要下面一段設定:

import matplotlib.pyplot as pltplt.rcParams['font.sas-serig']=['SimHei'] #用來正常顯示中文標籤plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

matplotlib inline和pylab inline

可以使用ipython --pylab開啟ipython命名視窗。

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

這兩個命令都可以在繪圖時,將圖片內嵌在互動視窗,而不是彈出一個圖片視窗,但是,有一個缺陷:除非將代碼一次執行,否則,無法疊加繪圖,因為在這兩種模式下,是要有plt出現,圖片會立馬show出來,因此:

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

為項目設定matplotlib參數

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

  1. 使用參數字典(rcParams)
  2. 調用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 白色

如果這兩種顏色不夠用,還可以通過兩種其他方式來定義顏色值:

  1. 使用HTML十六進位字串color='eeefff'使用合法的HTML顏色名字('red','chartreuse'等)。
  2. 也可以傳入一個歸一化到[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].

確定座標範圍plt.axis([xmin, xmax, ymin, ymax])

上面例子裡的axis()命令給定了座標範圍。

xlim(xmin, xmax)和ylim(ymin, ymax)來調整x,y座標範圍

%matplotlib inlineimport numpy as npimport matplotlib.pyplot as pltfrom 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 npimport matplotlib.pyplot as plt# evenly sampled time at 200ms intervalst = np.arange(0., 5., 0.2)# red dashes, blue squares and green trianglesplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show()

plt.figure()

你可以多次使用figure命令來產生多個圖,其中,圖片號按順序增加。這裡,要注意一個概念當前圖和當前座標。所有繪圖操作僅對當前圖和當前座標有效。通常,你並不需要考慮這些事,下面的這個例子為大家示範這一細節。

import matplotlib.pyplot as pltplt.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 npimport matplotlib.pyplot as pltmu, sigma = 100, 15x = 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 npimport matplotlib.pyplot as pltax = 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)的圖,並設定解析度為 80figure(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 packagesimport pandas as pd%matplotlib inlineimport matplotlib.pyplot as pltplt.style.use('ggplot')from sklearn import datasetsfrom sklearn import linear_modelimport numpy as np# Load databoston = datasets.load_boston()yb = boston.target.reshape(-1, 1)Xb = boston['data'][:,5].reshape(-1, 1)# Plot dataplt.scatter(Xb,yb)plt.ylabel('value of house /1000 ($)')plt.xlabel('number of rooms')# Create linear regression objectregr = linear_model.LinearRegression()# Train the model using the training setsregr.fit( Xb, yb)# Plot outputsplt.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對象都是一個擁有自己座標系統的繪圖區域。其邏輯關係如下:

plt.axes-官方文檔

  1. axes() by itself creates a default full subplot(111) window axis.
  2. 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.
  3. 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:

import matplotlib.pyplot as pltimport numpy as np# create some data to use for the plotdt = 0.001t = np.arange(0.0, 10.0, dt)r = np.exp(-t[:1000]/0.05)        # impulse responsex = np.random.randn(len(t))s = np.convolve(x, r)[:len(x)]*dt # colored noise# the main axes is subplot(111) by defaultplt.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 axesa = 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 axesa = 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參數

matplotlib.pyplot.pie

colors顏色

找出matpltlib.pyplot.plot中的colors可以取哪些值?

  1. so-Named colors in matplotlib
  2. matplotlib學習之設定線條顏色、形狀 
for name,hex in matplotlib.colors.cnames.iteritems():  print name,hex

列印顏色值和對應的RGB值。

plt.axis('equal')避免比例壓縮為橢圓

autopct

How do I use matplotlib 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.
 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.