標籤:too 知識 baidu bar png att 1.3 nbsp 資料
Matplotlib簡述: Matplotlib是一個用於建立出高品質圖表的案頭繪圖包(主要是2D方面)。該項目是由John Hunter於2002年啟動的,其目的是為Python構建一個MATLAB式的繪圖介面。如果結合Python IDE使用比如PyCharm,matplotlib還具有諸如縮放和平移等互動功能。它不僅支援各種作業系統上許多不同的GUI後端,而且還能將圖片匯出為各種常見的向量(vector)和光柵(raster)圖:PDF、SVG、JPG、PNG、BMP、GIF等。 此外,Matplotlib還有許多外掛程式工具集,如用於3D圖形的mplot3d以及用於地圖和投影的basemap。準備資料:從文字檔中解析資料(資料來源於《機器學習實戰》第二章 k鄰近演算法)datingTestSet2.txt檔案:https://pan.baidu.com/s/1pLwZRsv 本文使用的資料主要包含以下三種特徵:每年獲得的飛行常客裡程數,玩視頻遊戲所耗時間百分比,每周消費的冰淇淋公升數。其中分類結果作為檔案的第四列,並且只有3、2、1三種分類值。datingTestSet2.csv檔案格式如下所示:
| 飛行裡程數 |
遊戲耗時百分比 |
冰淇淋公升數 |
分類結果 |
| 40920 |
8.326976 |
0.953952 |
3 |
| 14488 |
7.153469 |
1.673904 |
2 |
| 26052 |
1.441871 |
0.805124 |
1 |
| ...... |
...... |
...... |
...... |
資料在datingTestSet2.txt檔案中的格式如下所示:
上述特徵資料的格式經過file2matrix函數解析處理之後,可輸出為矩陣和類標籤向量。將文本記錄轉換為Numpy的解析程式,將以下代碼儲存在kNN.py中:
from numpy import *def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = zeros((numberOfLines, 3)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split(‘\t‘) returnMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVector
使用file2matrix讀取檔案資料,必須確保待解析檔案儲存體在當前的工作目錄中。匯入資料之後,簡單檢查一下資料格式:
>>>import kNN>>>datingDataMat,datingLabels = kNN.file2matrix(‘datingTestSet2.txt‘)>>>datingDataMat[0:6]array([[ 4.09200000e+04, 8.32697600e+00, 9.53952000e-01], [ 1.44880000e+04, 7.15346900e+00, 1.67390400e+00], [ 2.60520000e+04, 1.44187100e+00, 8.05124000e-01], [ 7.51360000e+04, 1.31473940e+01, 4.28964000e-01], [ 3.83440000e+04, 1.66978800e+00, 1.34296000e-01], [ 7.29930000e+04, 1.01417400e+01, 1.03295500e+00]])>>> datingLabels[0:6][3, 2, 1, 1, 1, 1]
分析資料:使用Matplotlib建立散佈圖
編輯kNN.py檔案,引入matplotlib,調用matplotlib的scatter繪製散佈圖。
>>> import matplotlib>>> import matplotlib.pyplot as plt>>> fig = plt.figure()>>> ax = fig.add_subplot(111)>>> ax.scatter(datingDataMat[:,1],datingDataMat[:,2])<matplotlib.collections.PathCollection object at 0x0000019E14C9A470>>>> plt.show()>>>
產生的散佈圖如下:
散佈圖使用datingDataMat矩陣的第二、第三列資料,分別表示特徵值“玩視頻遊戲所耗時間百分比”和“每周消費的冰淇淋公升數”。kNN.py完整代碼如下:
import matplotlibimport numpy as npfrom numpy import *from matplotlib import pyplot as plt def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = zeros((numberOfLines, 3)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split(‘\t‘) returnMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVector datingDataMat,datingLabels = file2matrix(‘datingTestSet2.txt‘)fig = plt.figure()ax = plt.subplot(111)ax.scatter(datingDataMat[:,1],datingDataMat[:,2])plt.show()
由於沒有使用樣本分類的特徵值,很難看到任何有用的資料模式資訊。為了更好理解資料資訊,Matplotlib庫提供的scatter函數支援個人化標記散佈圖上的點。調用scatter函數使用下列參數:
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
產生的散佈圖如下:
利用datingLabels儲存的類標籤屬性,在散佈圖上繪製了色彩不等、尺寸不同的點。因而基本上可以看到資料點所屬三個樣本分類的地區輪廓。為了得到更好的效果,採用datingDataMat矩陣的屬性列1和2展示資料,並以紅色的‘*‘表示類標籤1、藍色的‘o‘表示表示類標籤2、綠色的‘+‘表示類標籤3,修改參數如下:
import matplotlibimport numpy as npfrom numpy import *from matplotlib import pyplot as pltfrom matplotlib.font_manager import FontProperties def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = zeros((numberOfLines, 3)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split(‘\t‘) returnMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVectorzhfont = FontProperties(fname=‘C:/Windows/Fonts/simsun.ttc‘,size=12) datingDataMat,datingLabels = file2matrix(‘datingTestSet2.txt‘)fig = plt.figure()plt.figure(figsize=(8, 5), dpi=80)ax = plt.subplot(111)datingLabels = np.array(datingLabels)idx_1 = np.where(datingLabels==1)p1 = ax.scatter(datingDataMat[idx_1,0],datingDataMat[idx_1,1],marker = ‘*‘,color = ‘r‘,label=‘1‘,s=10)idx_2 = np.where(datingLabels==2)p2 = ax.scatter(datingDataMat[idx_2,0],datingDataMat[idx_2,1],marker = ‘o‘,color =‘g‘,label=‘2‘,s=20)idx_3 = np.where(datingLabels==3)p3 = ax.scatter(datingDataMat[idx_3,0],datingDataMat[idx_3,1],marker = ‘+‘,color =‘b‘,label=‘3‘,s=30)plt.xlabel(u‘每年擷取的飛行裡程數‘, fontproperties=zhfont)plt.ylabel(u‘玩視頻遊戲所消耗的事件百分比‘, fontproperties=zhfont)ax.legend((p1, p2, p3), (u‘不喜歡‘, u‘魅力一般‘, u‘極具魅力‘), loc=2, prop=zhfont)plt.show()
產生的散佈圖如下:
第二種方法:
import matplotlibfrom matplotlib import pyplot as pltfrom matplotlib import font_manager def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = zeros((numberOfLines, 3)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split(‘\t‘) returnMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVectormatrix, labels = file2matrix(‘datingTestSet2.txt‘)zhfont = matplotlib.font_manager.FontProperties(fname=‘C:/Windows/Fonts/simsun.ttc‘,size=12) plt.figure(figsize=(8, 5), dpi=80)axes = plt.subplot(111)# 將三類資料分別取出來# x軸代表飛行的裡程數# y軸代表玩視頻遊戲的百分比type1_x = []type1_y = []type2_x = []type2_y = []type3_x = []type3_y = []for i in range(len(labels)): if labels[i] == 1: # 不喜歡 type1_x.append(matrix[i][0]) type1_y.append(matrix[i][1]) if labels[i] == 2: # 魅力一般 type2_x.append(matrix[i][0]) type2_y.append(matrix[i][1]) if labels[i] == 3: # 極具魅力 #print (i, ‘:‘, labels[i], ‘:‘, type(labels[i])) type3_x.append(matrix[i][0]) type3_y.append(matrix[i][1]) type1 = axes.scatter(type1_x, type1_y, s=20, c=‘red‘)type2 = axes.scatter(type2_x, type2_y, s=40, c=‘green‘)type3 = axes.scatter(type3_x, type3_y, s=50, c=‘blue‘)plt.xlabel(u‘每年擷取的飛行裡程數‘, fontproperties=zhfont)plt.ylabel(u‘玩視頻遊戲所消耗的事件百分比‘, fontproperties=zhfont)axes.legend((type1, type2, type3), (u‘不喜歡‘, u‘魅力一般‘, u‘極具魅力‘), loc=2, prop=zhfont)plt.show()
產生的散佈圖如下:
總結:本文簡單介紹了Matplotlib,並以執行個體分析了如何使用Matplotlib庫圖形化展示資料,最後通過修改matplotlib的scatter函數參數使得散佈圖的分類地區更加清晰。附加知識點:1、在使用Matplotlib組建圖表時,預設不支援漢字,所有漢字都會顯示成框框。解決方案:代碼中指定中文字型
# -*- coding: utf-8 -*-import matplotlib.pyplot as pltimport matplotlibzhfont1 = matplotlib.font_manager.FontProperties(fname=‘C:/Windows/Fonts/simsun.ttc‘) plt.xlabel(u"橫座標xlabel",fontproperties=zhfont1)
到C:\Windows\Fonts\中找到新宋體對應的字型檔simsun.ttf(Window 8和Windows10系統是simsun.ttc,也可以使用其他字型)
2、ax = fig.add_subplot(111) 返回Axes執行個體 參數一, 子圖總行數 參數二, 子圖總列數 參數三, 子圖位置 在Figure上添加Axes的常用方法
Python資料視覺效果——使用Matplotlib建立散佈圖