1. 程式人生 > >Python數據可視化——使用Matplotlib創建散點圖

Python數據可視化——使用Matplotlib創建散點圖

obj 工作目錄 復制 轉換 .fig utf ont 指定 後端

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 matplotlib
import numpy as np
from 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 matplotlib
import numpy as np
from numpy import *
from matplotlib import pyplot as plt
from 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, classLabelVector
zhfont = 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 matplotlib
from matplotlib import pyplot as plt
from 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, classLabelVector

matrix, 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 plt
import matplotlib
zhfont1 = 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創建散點圖