Python数据可视化——使用Matplotlib创建散点图
Python数据可视化——使用Matplotlib创建散点图
2017-12-27
作者:淡水化合物
| 飞行里程数 | 游戏耗时百分比 | 冰淇淋公升数 | 分类结果 |
| 40920 | 8.326976 | 0.953952 | 3 |
| 14488 | 7.153469 | 1.673904 | 2 |
| 26052 | 1.441871 | 0.805124 | 1 |
| ...... | ...... | ...... | ...... |
数据在datingTestSet2.txt文件中的格式如下所示:

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创建散点图
>>> 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()
>>>
生成的散点图如下:

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))
生成的散点图如下:

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='',s=10)
idx_2 = np.where(datingLabels==2)
p2 = ax.scatter(datingDataMat[idx_2,0],datingDataMat[idx_2,1],marker = 'o',color ='g',label='',s=20)
idx_3 = np.where(datingLabels==3)
p3 = ax.scatter(datingDataMat[idx_3,0],datingDataMat[idx_3,1],marker = '+',color ='b',label='',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()
生成的散点图如下:

# -*- 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,也可以使用其他字体)
Python数据可视化——使用Matplotlib创建散点图的更多相关文章
- python 数据可视化(matplotlib)
matpotlib 官网 :https://matplotlib.org/index.html matplotlib 可视化示例:https://matplotlib.org/gallery/inde ...
- Python数据可视化库-Matplotlib(一)
今天我们来学习一下python的数据可视化库,Matplotlib,是一个Python的2D绘图库 通过这个库,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率图,条形图,错误图,散点图等等 废 ...
- Python数据可视化之Matplotlib实现各种图表
数据分析就是将数据以各种图表的形式展现给领导,供领导做决策用,因此熟练掌握饼图.柱状图.线图等图表制作是一个数据分析师必备的技能.Python有两个比较出色的图表制作框架,分别是Matplotlib和 ...
- Python数据可视化利器Matplotlib,绘图入门篇,Pyplot介绍
Pyplot matplotlib.pyplot是一个命令型函数集合,它可以让我们像使用MATLAB一样使用matplotlib.pyplot中的每一个函数都会对画布图像作出相应的改变,如创建画布.在 ...
- Python数据可视化之matplotlib
常用模块导入 import numpy as np import matplotlib import matplotlib.mlab as mlab import matplotlib.pyplot ...
- 《机器学习实战》2.2.2分析数据:使用matplotlib创建散点图
#输出散点图 def f(): datingDataMat,datingLabels = file2matrix("datingTestSet3.txt") fig = plt.f ...
- Python数据可视化库-Matplotlib(二)
我们接着上次的继续讲解,先讲一个概念,叫子图的概念. 我们先看一下这段代码 import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.a ...
- python数据可视化(matplotlib)
- Python的可视化包 – Matplotlib 2D图表(点图和线图,.柱状或饼状类型的图),3D图表(曲面图,散点图和柱状图)
Python的可视化包 – Matplotlib Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型地2D图表和一些基本的3D图表.Matplotlib最早是为了可 ...
随机推荐
- Python之matplotlib模块安装
numpy 1.下载安装 源代码 http://sourceforge.net/projects/numpy/files/NumPy/ 安装 python2.7 setup.py install 2. ...
- 基于MyBatis的数据服务接口
背景 作为软件系统开发,数据操作是系统开发不可避免的一个重要组成部分.因为其重要性围绕着数据操作也出现了众多框架.成熟框架是为了普适众多数据操作要求的,因此为了更好的实现技术落地,需要对框架进行丰富和 ...
- Python [习题] 字典扁平化
习题: 将以下字典扁平化,输出为 target 字典格式source = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': {'g': 4}}}target = { ...
- pyqt5实现注册界面
__author__ = 'sign_in' import sys from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import * clas ...
- 《java.util.concurrent 包源码阅读》12 线程池系列之ThreadPoolExecutor 第二部分
接着说worker线程是如何工作的.ThreadPoolExecutor有一个成员类叫Worker,所起到的作用就是线程池worker线程的作用. private final class Worker ...
- jq获取被选中的option的值。jq获取被选中的单选按钮radio的值。
温故而知新,一起复习下jq的知识点. (1) jq获取被选中的option的值 <select id="select_id"> <option value=&qu ...
- 2386:Lake Counting-poj
总时间限制: 1000ms 内存限制: 65536kB 描述 Due to recent rains, water has pooled in various places in Farmer J ...
- jQuery中使用$.each()遍历后台响应的json字符串问题
今天在做练习项目的时候,使用$.each()方法遍历后台传过来的json字符串时,chrome浏览器中发现如下问题 Cannot use 'in' operator to search for 'l ...
- NodeJS爬虫入门
1. 写在前面 往常都是利用 Python/.NET 语言实现爬虫,然现在作为一名前端开发人员,自然需要熟练 NodeJS.下面利用 NodeJS 语言实现一个糗事百科的爬虫.另外,本文使用的部分代码 ...
- jQuer __Ajax DOM
链接:在线jQueryhttp://www.bootcdn.cn 一.each(遍历) $("ul li").each(function(index,value){ ale ...