Python:如何使用示例创建图例

Python:如何使用示例创建图例,python,numpy,matplotlib,plot,legend,Python,Numpy,Matplotlib,Plot,Legend,这是《机器学习在行动》一书第2章中的内容,我正试图画出图中的情节: 作者已经发布了情节的代码,我认为这可能有点黑客(他还提到这段代码很草率,因为它超出了本书的范围) 以下是我重新创建绘图的尝试: 首先,保存数据的.txt文件如下所示(来源:Ch.2中的“datingTestSet2.txt”): 假设datingDataMat是一个numpy.ndarray形状的`(1000L,2L),其中第0列是“常客每年的里程”,第1列是“玩视频游戏的时间”,第2列是“每周消耗的冰淇淋升”,如上面的示例所

这是《机器学习在行动》一书第2章中的内容,我正试图画出图中的情节:

作者已经发布了情节的代码,我认为这可能有点黑客(他还提到这段代码很草率,因为它超出了本书的范围)

以下是我重新创建绘图的尝试:

首先,保存数据的.txt文件如下所示(来源:Ch.2中的“datingTestSet2.txt”):

假设
datingDataMat
是一个
numpy.ndarray
形状的`(1000L,2L),其中第0列是“常客每年的里程”,第1列是“玩视频游戏的时间”,第2列是“每周消耗的冰淇淋升”,如上面的示例所示

假设
datingLabels
是一个
列表,包含int 1、2或3,分别表示“不喜欢”、“小剂量喜欢”和“大剂量喜欢”——与上面第3列相关

下面是我必须创建绘图的代码(末尾是
file2matrix
的完整详细信息):

输出如下:

我主要关心的是如何创造这个传奇。有没有一种方法可以做到这一点而不需要直接处理这些点

接下来,我想知道我是否能找到一种方法来切换颜色以匹配那些情节。有没有一种方法可以做到这一点,而不必对个别问题进行某种“处理”

另外,如果有兴趣,这里是
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

要创建图例,您必须:

  • 为每条曲线指定标签

  • 从当前的
    AxesSubplot
    对象调用
    legend()
    方法,例如,可以使用
    plt.gca()
    获得该对象

请参见下面的示例:

plt.scatter(datingDataMat[:,0], datingDataMat[:,1],
            15.0*np.array(datingLabels), 15.0*np.array(datingLabels),
            label='Label for this data')
plt.gca().legend(loc='upper left')

下面是一个模拟您已有代码的示例,该代码显示了Saullo Castro示例中描述的方法。 它还显示了如何在示例中设置颜色。 如果需要有关可用颜色的更多信息,请参阅

此外,还值得在以下位置查看散点图文档:

如果使用
plt.savefig
将图形保存到文件而不是显示,则灰色边框应变为白色。
请记住在保存到文件后运行
plt.clf()
plt.cla()
,以清除轴,这样您就不会一次又一次地在其上重复相同的数据。

很好的一行文字来放置图例。很高兴知道。
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
plt.scatter(datingDataMat[:,0], datingDataMat[:,1],
            15.0*np.array(datingLabels), 15.0*np.array(datingLabels),
            label='Label for this data')
plt.gca().legend(loc='upper left')
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()