Python:如何使用示例创建图例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:如何使用示例创建图例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3320字,纯文字阅读大概需要5分钟。
内容图文
![Python:如何使用示例创建图例](/upload/InfoBanner/zyjiaocheng/678/2d8fb90208fa40fe9c499f3f986d2ec1.jpg)
这是《机器学习在行动》一书的第2章中的内容,我正在尝试绘制如下图:
作者发布了该地块的代码here,我认为这可能有点怪(他还提到此代码草率,因为它不在本书的范围之内).
这是我尝试重新创建图的尝试:
首先,保存数据的.txt文件如下(来源:Ch.2 here中的“ datingTestSet2.txt”):
40920 8.326976 0.953952 largeDoses
14488 7.153469 1.673904 smallDoses
26052 1.441871 0.805124 didntLike
75136 13.147394 0.428964 didntLike
38344 1.669788 0.134296 didntLike
...
假设dateingDataMat是一个形状为((1000L,2L)的numpy.ndarray,其中第0列是“每年的飞行里程”,第1列是“玩视频游戏的时间百分比”,第2列是“每周消耗的冰淇淋升”,如上面的示例所示.
假设约会标签是整数1、2或3的列表,分别表示“不喜欢”,“喜欢小剂量”和“喜欢大剂量”,与上面的第3列相关联.
这是我必须创建情节的代码(file2matrix的完整详细信息在最后):
datingDataMat,datingLabels = file2matrix("datingTestSet2.txt")
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot (111)
plt.xlabel("Freq flier miles")
plt.ylabel("% time video games")
# Not sure how to finish this: plt.legend([1, 2, 3], ["did not like", "small doses", "large doses"])
plt.scatter(datingDataMat[:,0], datingDataMat[:,1], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels)) # Change marker color and size
plt.show()
输出在这里:
我主要关心的是如何创建此图例.有没有办法直接处理这些要点?
接下来,我很好奇是否可以找到一种方法来切换颜色以匹配情节的颜色.有没有一种方法可以在各个点上都没有某种“处理”?
另外,如果有兴趣,这里是file2matrix实现:
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines())
returnMat = np.zeros((numberOfLines,3)) #numpy.zeros(shape, dtype=float, order='C')
classLabelVector = []
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3] # FFmiles/yr, % time gaming, L ice cream/wk
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
解决方法:
这是一个模仿您已有代码的示例,该示例显示了Saullo Castro的示例中描述的方法.
它还在示例中显示了如何设置颜色.
如果需要有关可用颜色的更多信息,请参阅文档,网址为http://matplotlib.org/api/colors_api.html
值得一看的是散点图文档,网址为http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter
from numpy.random import rand, randint
from matplotlib import pyplot as plt
n = 1000
# Generate random data
data = rand(n, 2)
# Make a random array to mimic datingLabels
labels = randint(1, 4, n)
# Separate the data according to the labels
data_1 = data[labels==1]
data_2 = data[labels==2]
data_3 = data[labels==3]
# Plot each set of points separately
# 's' is the size parameter.
# 'c' is the color parameter.
# I have chosen the colors so that they match the plot shown.
# With each set of points, input the desired label for the legend.
plt.scatter(data_1[:,0], data_1[:,1], s=15, c='r', label="label 1")
plt.scatter(data_2[:,0], data_2[:,1], s=30, c='g', label="label 2")
plt.scatter(data_3[:,0], data_3[:,1], s=45, c='b', label="label 3")
# Put labels on the axes
plt.ylabel("ylabel")
plt.xlabel("xlabel")
# Place the Legend in the plot.
plt.gca().legend(loc="upper left")
# Display it.
plt.show()
如果使用plt.savefig将图形保存到文件而不是显示图形,则灰色边框应变为白色.
请记住在保存到文件中以清除轴后再运行plt.clf()或plt.cla(),以免最终不要一遍又一遍地重新绘制相同数据.
内容总结
以上是互联网集市为您收集整理的Python:如何使用示例创建图例全部内容,希望文章能够帮你解决Python:如何使用示例创建图例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。