matplotlib的传说

2024-07-02 09:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文

from numpy import *
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches

def file2martix(filename):
    fr = open(filename)



    arryOfLines = fr.readlines()
    numbersOfLines = len(arryOfLines)
    print(numbersOfLines)
    returnMat = zeros((numbersOfLines,3))
    print(returnMat)


    classLableVector = []
    index = 0
    for line in arryOfLines:
        line = line.strip() 
        listFromLine = line.split('\t') 
        returnMat[index,:] = listFromLine[0:3]
        print(listFromLine[0:3])
        classLableVector.append(int(listFromLine[-1]))
        index = index + 1
    return returnMat,classLableVector

datingDataMat,datingLables = file2martix('1.txt')


fig = plt.figure()
ax = fig.add_subplot(111)
color = ['yellow','green','blue']
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],s = 15,c = color)
print(datingLables)


plt.legend(color[0:2], loc=0, ncol=4)



plt.show()

如您所见,我将color设置为label来控制函数legend,color是一个列表。 问题是运行时,图片中的图例仅显示第一个元素-“黄色” 怎么了? 我希望这幅画的传说能说明这一点的三个要素

我喜欢通过创造三个情节来解决这个问题,虽然有颜色的情节可以一个接一个。你知道吗

handlelist = [plt.plot([],color=color)[0] for color in colors]

plt.legend(handlelist,colors,loc=0, ncol=4)

Tags: importindexmatplotliblinepltcolorprintlegend