生成的散点图如下:
第二种方法:
- import matplotlib
- from matplotlib import pyplot as plt
- from matplotlib import font_manager
- def file2matrix(filename):
- fr = open(filename)
- numberOfLines = len(fr.readlines()) # get the number of lines in the file
- returnMat = zeros((numberOfLines, 3)) # prepare matrix to return
- classLabelVector = [] # prepare labels return
- fr = open(filename)
- index = 0
- for line in fr.readlines():
- line = line.strip()
- listFromLine = line.split('\t')
- returnMat[index, :] = listFromLine[0:3]
- classLabelVector.append(int(listFromLine[-1]))
- index += 1
- return returnMat, classLabelVector
- matrix, labels = file2matrix('datingTestSet2.txt')
- zhfont = matplotlib.font_manager.FontProperties(fname='C:/Windows/Fonts/simsun.ttc',size=12)
- plt.figure(figsize=(8, 5), dpi=80)
- axes = plt.subplot(111)
- # 将三类数据分别取出来
- # x轴代表飞行的里程数
- # y轴代表玩视频游戏的百分比
- type1_x = []
- type1_y = []
- type2_x = []
- type2_y = []
- type3_x = []
- type3_y = []
- for i in range(len(labels)):
- if labels[i] == 1: # 不喜欢
- type1_x.append(matrix[i][0])
- type1_y.append(matrix[i][1])
- if labels[i] == 2: # 魅力一般
- type2_x.append(matrix[i][0])
- type2_y.append(matrix[i][1])
- if labels[i] == 3: # 极具魅力
- #print (i, ':', labels[i], ':', type(labels[i]))
- type3_x.append(matrix[i][0])
- type3_y.append(matrix[i][1])
- type1 = axes.scatter(type1_x, type1_y, s=20, c='red')
- type2 = axes.scatter(type2_x, type2_y, s=40, c='green')
- type3 = axes.scatter(type3_x, type3_y, s=50, c='blue')
- plt.xlabel(u'每年获取的飞行里程数', fontproperties=zhfont)
- plt.ylabel(u'玩视频游戏所消耗的事件百分比', fontproperties=zhfont)
- axes.legend((type1, type2, type3), (u'不喜欢', u'魅力一般', u'极具魅力'), loc=2, prop=zhfont)
- plt.show()
生成的散点图如下:
- # -*- coding: utf-8 -*-
- import matplotlib.pyplot as plt
- import matplotlib
- zhfont1 = matplotlib.font_manager.FontProperties(fname='C:/Windows/Fonts/simsun.ttc')
- plt.xlabel(u"横坐标xlabel",fontproperties=zhfont1)
到 C:\Windows\Fonts \ 中找到新宋体对应的字体文件 simsun.ttf(Window 8 和 Windows10 系统是 simsun.ttc,也可以使用其他字体)
来源: https://www.cnblogs.com/pengsky2016/p/8126623.html