import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def draw_diagram(data_set, data_labels):
plt.figure()
ax = plt.subplot(111, projection='3d')
plt.rcParams['font.sans-serif'] = ['Simhei'] # 字体
plt.rcParams['axes.unicode_minus'] = False # 编码
type1_x = []
type1_y = []
type1_z = []
type2_x = []
type2_y = []
type2_z = []
type3_x = []
type3_y = []
type3_z = []
for i in range(len(data_set)):
if data_labels[i] == 1:
type1_x.append(data_set[i][0])
type1_y.append(data_set[i][1])
type1_z.append(data_set[i][2])
if data_labels[i] == 2:
type2_x.append(data_set[i][0])
type2_y.append(data_set[i][1])
type2_z.append(data_set[i][2])
if data_labels[i] == 3:
type3_x.append(data_set[i][0])
type3_y.append(data_set[i][1])
type3_z.append(data_set[i][2])
ax.scatter(type1_x, type1_y, type1_z, c='r', label='不喜欢')
ax.scatter(type2_x, type2_y, type2_z, c='b', label='一般魅力')
ax.scatter(type3_x, type3_y, type3_z, c='k', label='很有魅力')
ax.set_zlabel('Z') # 坐标轴
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.legend() # 添加注释
plt.show()
在学习KNN算法时遇到的约会网站的数据,该数据共有四列,前三列为特征值,最后一列为类别。这里使用python语言的matplotlib库对这些数据进行可视化展示。