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最早是为了可 ...
随机推荐
- [转载] 解读ClassLoader
转载自http://www.iteye.com/topic/83978 ClassLoader一个经常出现又让很多人望而却步的词,本文将试图以最浅显易懂的方式来讲解 ClassLoader,希望能对不 ...
- Postman+newman+jenkins构建
最近忙着项目接口测试,经过不同工具的对比,发现postman使用起来挺顺手的,所以马上决定使用这个工具进行接口测试工作.刚开始的时候,了解了下接口测试的相关信息,直接着手编写接口测试的测试用例信息 ...
- Python 动态添加类方法
习题: 1. Shape基类,要求所有子类都必须提供面积的计算,子类有三角形.矩形.圆. 2. 上题圆类的数据可序列化 第一种方法:使用Mixin多继承组合的方式,混入其它类的属性和方法 第二种方法: ...
- 一步一步带你实现virtual dom(二) -- Props和事件
很高兴我们可以继续分享编写虚拟DOM的知识.这次我们要讲解的是产品级的内容,其中包括:设置和DOM一致性.以及事件的处理. 使用Babel 在继续之前,我们需要弥补前一篇文章中没有详细讲解的内容.假设 ...
- (译)学习JavaScript闭包
原文地址:https://medium.freecodecamp.org/lets-learn-javascript-closures-66feb44f6a44 闭包是JavaScript中一个基 ...
- 2778:Ride to School-poj
2778:Ride to School 总时间限制: 1000ms 内存限制: 65536kB 描述 Many graduate students of Peking University are ...
- RibbonForm使用技巧
Ribbon右侧显示Logo 方法 重写RibbonControl的Paint事件 效果 代码 private void _ribbonControl_Paint(object sender, Pai ...
- codeforces #446 892A Greed 892B Wrath 892C Pride 891B Gluttony
A 链接:http://codeforces.com/problemset/problem/892/A 签到 #include <iostream> #include <algor ...
- CCF-201604-3-路径解析
问题描述 试题编号: 201604-3 试题名称: 路径解析 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 在操作系统中,数据通常以文件的形式存储在文件系统中.文件系统一般采 ...
- React学习笔记--程序调试
React学习笔记 二 程序调试 前面我们搭建好了React的基本开发环境,可以编写基本的React js程序了.但完成的开发环境肯定包含调试器,怎么调试用React编写的JS程序呢?有浏览器,比 ...