Python 更改matplotlib.pyplot点的颜色
以下是我编写的绘图代码:Python 更改matplotlib.pyplot点的颜色,python,matplotlib,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
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()
我正试图根据数组词汇表中的值更改颜色
如果1,则将数据点涂成红色,如果2,则涂成绿色,如果3,则涂成蓝色,否则将点涂成黑色。但对于所有点,每个点的颜色都设置为蓝色。如何根据词汇表的当前值为数据点着色
上述代码生成:
您可以制作一个颜色字典,并在散点图中查找它,如下所示
%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()
导致
您刚刚犯了一个小小的复制粘贴错误。
只是对你的风格的一点评论:在使用颜色列表时,你可以避免太多的“如果”,因此:
colors=[red,green,blue,black]
然后:
plt.annotate('', xy=(x, y), xytext=(0, 0), color=colors[max(3,label)] , textcoords='offset points')
您的代码必须如此,您总是编写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()