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

yipeiwu_com5年前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设计】。

相关文章

Windows下使Python2.x版本的解释器与3.x共存的方法

Python2 和 Python3 是不兼容的,如果碰到无法升级到 Python2 代码,或者同事中有坚守 Python2 阵营的情况,就要考虑 Python2 和 Python3 在系...

Python函数装饰器实现方法详解

本文实例讲述了Python函数装饰器实现方法。分享给大家供大家参考,具体如下: 编写函数装饰器 这里主要介绍编写函数装饰器的相关内容。 跟踪调用 如下代码定义并应用一个函数装饰器,来统计...

Django框架下在视图中使用模版的方法

 打开current_datetime 视图。 以下是其内容: from django.http import HttpResponse import datetime...

pygame实现贪吃蛇游戏(下)

pygame实现贪吃蛇游戏(下)

接着上篇pygame实现贪吃蛇游戏(上)继续介绍 1.豆子的吃掉效果 只需在代码最后移动蛇头的代码后增加一个蛇头和豆子坐标的判断即可 if snake_x == bean_x and...

python文件与目录操作实例详解

本文实例分析了python文件与目录操作的方法。分享给大家供大家参考,具体如下: 关于python文件操作的详细说明,大家可以参考前一篇《python文件操作相关知识点总结整理》 官方A...