python scatter散点图用循环分类法加图例

yipeiwu_com6年前Python基础

本文实例为大家分享了python scatter散点图用循环分类法加图例,供大家参考,具体内容如下

import matplotlib.pyplot as plt
import kNN
 
plt.rcParams['font.sans-serif']=['Simhei']
plt.rcParams['axes.unicode_minus']=False
 
datingDataMat, datingLabels = kNN.file2matrix('datingTestSet2.txt')
 
plt.figure()
type1_x = []  #一共有3类,所以定义3个空列表准备接受数据
type1_y = []
type2_x = []
type2_y = []
type3_x = []
type3_y = []
 
for i in range(len(datingLabels)):     #1000组数据,i循环1000次
  if datingLabels[i] == '1':        #根据标签进行数据分类,注意标签此时是字符串
    type1_x.append(datingDataMat[i][0]) #取的是样本数据的第一列特征和第二列特征
    type1_y.append(datingDataMat[i][1])
 
  if datingLabels[i] == '2':
    type2_x.append(datingDataMat[i][0])
    type2_y.append(datingDataMat[i][1])
 
  if datingLabels[i] == '3':
    type3_x.append(datingDataMat[i][0])
    type3_y.append(datingDataMat[i][1])
 
plt.scatter(type1_x, type1_y, s=20, c='r', label='不喜欢')
plt.scatter(type2_x, type2_y, s=40, c='b', label='魅力一般')
plt.scatter(type3_x, type3_y, s=60, c='k', label='极具魅力')
 
plt.legend()
plt.show()

用面向对象的写法:

import matplotlib.pyplot as plt
import kNN
 
plt.rcParams['font.sans-serif']=['Simhei']
plt.rcParams['axes.unicode_minus']=False
 
datingDataMat, datingLabels = kNN.file2matrix('datingTestSet2.txt')
 
plt.figure()
axes = plt.subplot(111)
 
type1_x = []
type1_y = []
type2_x = []
type2_y = []
type3_x = []
type3_y = []
 
for i in range(len(datingLabels)):
  if datingLabels[i] == '1':
    type1_x.append(datingDataMat[i][0])
    type1_y.append(datingDataMat[i][1])
 
  if datingLabels[i] == '2':
    type2_x.append(datingDataMat[i][0])
    type2_y.append(datingDataMat[i][1])
 
  if datingLabels[i] == '3':
    type3_x.append(datingDataMat[i][0])
    type3_y.append(datingDataMat[i][1])
 
type1 = axes.scatter(type1_x, type1_y, s=20, c='r')
type2 = axes.scatter(type2_x, type2_y, s=40, c='b')
type3 = axes.scatter(type3_x, type3_y, s=60, c='k')
 
plt.legend((type1, type2, type3), ('不喜欢', '魅力一般', '极具魅力'))
plt.show()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

探究数组排序提升Python程序的循环的运行效率的原因

早上我偶然看见一篇介绍两个Python脚本的博文,其中一个效率更高。这篇博文已经被删除,所以我没办法给出文章链接,但脚本基本可以归结如下: fast.py   impor...

Python学习笔记之图片人脸检测识别实例教程

Python学习笔记之图片人脸检测识别实例教程

前言 随着科技的发展,人脸识别技术在许多领域得到的非常广泛的应用,手机支付、银行身份验证、手机人脸解锁等等。 识别 废话少说,这里我们使用 opencv 中自带了 haar人脸特征分...

Python 内置变量和函数的查看及说明介绍

Python 内置变量和函数的查看及说明介绍

Python 解释器内置了一些常量和函数,叫做内置常量(Built-in Constants)和内置函数(Built-in Functions),我们怎么在 查看全部内置常量和函数的名字...

python使用opencv进行人脸识别

python使用opencv进行人脸识别

环境 ubuntu 12.04 LTS python 2.7.3 opencv 2.3.1-7 安装依赖 sudo apt-get install libopencv-* sudo...

实例讲解Python脚本成为Windows中运行的exe文件

将程序转换为exe文件 我们先来介绍如何使用工具Pyinstaller 安装Pyinstaller 我们用pip安装Pyinstaller 。 注意,如果使用Pyinstaller,则应...