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

每到春天,红得如火的木棉花,粉得如霞的芍药花,白得如玉的月季花竞相开放。它们有的花蕾满枝,有的含苞初绽,有的昂首怒放。一阵沁人心肺的花香引来了许许多多的小蜜蜂,嗡嗡嗡地边歌边舞。

本文实例为大家分享了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 scatter散点图用循环分类法加图例到此结束。话多不如话少,话少不如话好。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战