更改 matplotlib.pyplot 点的颜色

blu*_*sky 6 python matplotlib

这是我写的情节代码:

import matplotlib.pyplot as plt

Y = [ 1 , 2 , 3 ]
X = [ 1 , 2 , 4 ]
vocabulary = [1 , 2 , 3]

plt.scatter(X , Y)
for label, x, y in zip(vocabulary, X, Y):
    if(label == 1):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='red' , textcoords='offset points')
    elif(label == 1):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='green' , textcoords='offset points')
    elif(label == 1):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='blue' , textcoords='offset points')
    else :
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='black' , textcoords='offset points')
plt.show()
Run Code Online (Sandbox Code Playgroud)

我试图根据数组中的值更改颜色,vocabulary 如果 1 则将数据点着色为红色,如果 2 则将数据点着色为绿色,如果 3 则将数据点着色为蓝色,否则将数据点着色为黑色。但对于所有点,每个点的颜色都设置为蓝色。如何根据 的当前值对数据点着色vocabulary

上面的代码产生:

在此输入图像描述

pla*_*360 6

您可以制作一个颜色字典并在散点图中查找它,如下所示

%matplotlib inline
import matplotlib.pyplot as plt

Y = [ 1 , 2 , 3 ,6]
X = [ 1 , 2 , 4 ,5]
vocabulary = [1 , 2 , 3, 0]
my_colors = {1:'red',2:'green',3:'blue'}

for i,j in enumerate(X):
    # look for the color based on vocabulary, if not found in vocubulary, then black is returned.
    plt.scatter(X[i] , Y[i], color = my_colors.get(vocabulary[i], 'black'))

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果是

在此输入图像描述


LMD*_*LMD 4

您刚刚犯了一点复制和粘贴错误。只是对你的风格的评论:当使用颜色列表时,你可以避免这么多如果,所以:

colors=[red,green,blue,black]
Run Code Online (Sandbox Code Playgroud)

进而 :

plt.annotate('', xy=(x, y), xytext=(0, 0), color=colors[max(3,label)] , textcoords='offset points')
Run Code Online (Sandbox Code Playgroud)

你的代码必须是这样,你总是这样写elif label=1,这绝对没有意义:

import matplotlib.pyplot as plt

Y = [ 1 , 2 , 3 ]
X = [ 1 , 2 , 4 ]
vocabulary = [1 , 2 , 3]

plt.scatter(X , Y)
for label, x, y in zip(vocabulary, X, Y):
    if(label == 1):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='red' , textcoords='offset points')
    elif(label == 2):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='green' , textcoords='offset points')
    elif(label == 3):
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='blue' , textcoords='offset points')
    else :
        plt.annotate('', xy=(x, y), xytext=(0, 0), color='black' , textcoords='offset points')
plt.show()
Run Code Online (Sandbox Code Playgroud)