国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-01-04 15:37:24
字體:
來源:轉載
供稿:網友

無論你工作在什么項目上,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].

Python,matplotlib,繪圖,數據可視化,可視化

確定坐標范圍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)

Python,matplotlib,繪圖,數據可視化,可視化

疊加圖

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

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

Python,matplotlib,繪圖,數據可視化,可視化

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 的標題

Python,matplotlib,繪圖,數據可視化,可視化

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

Python,matplotlib,繪圖,數據可視化,可視化

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

Python,matplotlib,繪圖,數據可視化,可視化

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

Python,matplotlib,繪圖,數據可視化,可視化

當我們設置記號的時候,我們可以同時設置記號的標簽。注意這里使用了 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')

Python,matplotlib,繪圖,數據可視化,可視化

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

Python,matplotlib,繪圖,數據可視化,可視化

給特殊點做注釋

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

我們希望在 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"))

Python,matplotlib,繪圖,數據可視化,可視化

plt.subplot()

plt.subplot(2,3,1)表示把圖標分割成2*3的網格。也可以簡寫plt.subplot(231)。其中,第一個參數是行數,第二個參數是列數,第三個參數表示圖形的標號。

plt.axes()

我們先來看什么是Figure和Axes對象。在matplotlib中,整個圖像為一個Figure對象。在Figure對象中可以包含一個,或者多個Axes對象。每個Axes對象都是一個擁有自己坐標系統的繪圖區域。其邏輯關系如下:

Python,matplotlib,繪圖,數據可視化,可視化

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

Python,matplotlib,繪圖,數據可視化,可視化

pyplot.pie參數

matplotlib.pyplot.pie

colors顏色

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

  1. so-Named colors in 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.
 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜州市| 巴楚县| 济源市| 泰兴市| 渝北区| 酒泉市| 邵阳县| 昌宁县| 莱西市| 伊吾县| 新泰市| 房产| 巴东县| 阿拉善右旗| 宿迁市| 铜鼓县| 南充市| 连云港市| 龙川县| 渝中区| 长阳| 和静县| 耒阳市| 万山特区| 砚山县| 阳信县| 鄂伦春自治旗| 阿拉善左旗| 扎赉特旗| 铁力市| 图片| 武城县| 济宁市| 泊头市| 平潭县| 绥宁县| 宝清县| 洪泽县| 乌拉特后旗| 莲花县| 中超|