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最早是为了可 ...
随机推荐
- vue新手入门——谈谈理解
毕业到现在大概4个月了,从java开发慢慢转到前端开发(其实是因为公司前端人不够),然后开始接触vue.所以我也只是一只小菜鸟. 首先附上vue的官网:vue官网 然后附上一些常用的vue框架,组件之 ...
- [转载] Thrift-client与spring集成
转载自http://shift-alt-ctrl.iteye.com/blog/1990030?utm_source=tuicool&utm_medium=referral Thrift-cl ...
- Openstack的打包方法
使用setup.cfg和setup.py进行管理 1.setup.py文件内容 # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO ...
- (11.20)Java小知识!
经过一段时间的学习,我也终于来到了Java语言的核心篇,也就是对象与类的学习,今天想要和大家分享的是关于类的小知识点. 1.类的声明: 类可以看成创建Java对象的模板.类亦可以理解成Java一种 ...
- OC语言的Block与Protocol(协议)
Block ● Block封装了一段代码,可以在任何时候执⾏行 ● Block可以作为函数参数或者函数的返回值,⽽而其本⾝身又可以带输⼊入参数或返回值. ● 苹果官⽅方建议尽量多⽤用block.在多线 ...
- Django的分页器(paginator)
先导入模块: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger 分页器paginator 下面的所有方法 ...
- springMVC+commons-fileupload上传文件大小限制异常
异常信息: 严重: Servlet.service() for servlet [suibian] in context with path [/SpringMvcDemo3] threw excep ...
- 实践作业2:黑盒测试实践——小组任务分工 Day 1
今日教学实验任务分配后,课下小组例会完成任务分工,具体分工如下: (1)系统需求分析--刘思佳 (2)设计测试用例--王俊杰 (3)编写.运行测试脚本--郜昌磊 (4)记录测试过程--吴慧杰 (5)记 ...
- 实践作业1:测试管理工具实践 Day3
1.Vertrigoserv启动后,首先要配置apache,则需要修改监听端口,不要出现端口冲突2.配置mysql,在mysql console中输入密码vertrigo3.在浏览器中输入http:/ ...
- mysql left join 几个意思
left join 用于多表 >1个表比如select a.*,b.* from ta as a left join tb as b on a.aid=b.bid咱们就以实际的代码来查看一下. ...