利用颜色及尺寸标识了数据点的属性类别显示二维散点图,话不多说直接上代码:
#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()
下面是运行效果:
希望对大家有所帮助!