实例(Machine Learning in Action):
一般情况下,简单绘制散点图:
import matplotlib.pyplot as plt dating_data_mat, datingLabel = TxtToNumpy.TxtToNumpy("datingTestSet2.txt") fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot(111) #x轴、y轴、点大小、点颜色 ax.scatter(dating_data_mat[:, 0], dating_data_mat[:, 1], 15.0*array(datingLabel), 15.0*array(datingLabel)) plt.xlabel("Frequent Flyier Miles Earned Per Year") plt.ylabel("Percentage of Time Spent Playing Video Games") plt.show()
得到的图像:
加上legend,只需要将不同标签分类到几个数据集中,然后就可以按照分类来加legend了:
import matplotlib.pyplot as plt dating_data_mat, datingLabel = TxtToNumpy.TxtToNumpy("datingTestSet2.txt") type1_x = []; type1_y = [] type2_x = []; type2_y = [] type3_x = []; type3_y = [] for i in range(len(datingLabel)): if datingLabel[i] == 1: #第i行的label为1时 type1_x.append(dating_data_mat[i][0]) type1_y.append(dating_data_mat[i][1]) if datingLabel[i] == 2: #第i行的label为2时 type2_x.append(dating_data_mat[i][0]) type2_y.append(dating_data_mat[i][1]) if datingLabel[i] == 3: #第i行的label为3时 type3_x.append(dating_data_mat[i][0]) type3_y.append(dating_data_mat[i][1]) fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot(111) type1 = ax.scatter(type1_x, type1_y, s = 30, c = 'brown') type2 = ax.scatter(type2_x, type2_y, s = 30, c = 'lime') type3 = ax.scatter(type3_x, type3_y, s = 30, c = "darkviolet") plt.xlabel("Frequent Flyier Miles Earned Per Year") plt.ylabel("Percentage of Time Spent Playing Video Games") ax.legend((type1, type2, type3), ("DidntLike", "SmallDoses", "LargeDoses"), loc = 0) plt.show()
得到的图像: