机器学习实战用Python中的Matplotlib库创建二维、三维散点图

利用颜色及尺寸标识了数据点的属性类别显示二维散点图,话不多说直接上代码:

#import kNN
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
#reload(kNN)
datingDataMat,datingLabels=kNN.file2matrix('datingTestSet2.txt')
fig=plt.figure()
ax=fig.add_subplot(111)
#ax.scatter(datingDataMat[:,1],datingDataMat[:,2])
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
plt.show()

下面是显示运行效果图:
在这里插入图片描述
在给坐标添加中文标签的时候遇到的方框问题,下面是给坐标添加标签以及三维散点图的代码:

import kNN
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
from pylab import * 
from matplotlib import rcParams#添加可显示中文,把方框换成文字
rcParams['font.family'] = 'simhei'#添加可显示中文
from mpl_toolkits.mplot3d import Axes3D  #导入3维图像的包

#定义三个类别的空列表
type1_x = []
type1_y = []
type2_x = []
type2_y = []
type3_x = []
type3_y = []
datingDataMat,datingLabels=kNN.file2matrix('datingTestSet2.txt')
fig=plt.figure()
ax=fig.add_subplot(221)#代表创建1行1列从上到下的第三块的子图

#循环获得每个列表中的值
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 = ax.scatter(type1_x, type1_y, s=20, c='red')
type2 = ax.scatter(type2_x, type2_y, s=40, c='green')
type3 = ax.scatter(type3_x, type3_y, s=50, c='blue')
ax.legend((type1, type2, type3), (u'不喜欢', u'魅力一般', u'极具魅力'), loc=2)#显示图例  1 右上  2左上 3左下 4 右下 逆时针
#ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0*array(datingLabels))
plt.xlabel(u'x  每年获取的飞行常客里程数')  
plt.ylabel(u'y  玩视频游戏所耗时间半分比')
plt.title(u'图一(1&&2)')

#————————————————三维
#第二个图 是第1个特征和第2个特征和第3个特征的散点图
fig2 = plt.figure() #创建图形
ax = fig2.add_subplot(222)
ax = Axes3D(fig2)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels),15.0*array(datingLabels))
ax.set_xlabel(u'x  每年获取的飞行常客里程数')
ax.set_ylabel(u'y  玩视频游戏所耗时间半分比')
ax.set_zlabel(u'z  每周消费的冰淇淋公升数')
plt.title(u'图二(1&&2&&3)')
plt.show()

下面是运行效果:
在这里插入图片描述
希望对大家有所帮助!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值