当前位置: 移动技术网 > IT编程>脚本编程>Python > python scatter散点图用循环分类法加图例

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

2019年06月12日  | 移动技术网IT编程  | 我要评论

大连周水子机场航班,滥竽充数的道理,点菜网

本文实例为大家分享了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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网