每次创建绘图时生成不同的随机颜色

时间:2016-10-23 14:21:54

标签: python plot colors line scatter

X = [22,33,55,66,77,55,66,77,44,66,33] Y = [2,6,9,9,10,5,32,19,123,46,93]

list = [0,1,2,3,4,0,5,6,7,8,8,9,10,0]

x和y是坐标 list表示算法输出序列

使用列表我需要绘制不同的颜色,在这个例子中:  1,2,3,4 - ColorA  5,6,7 - ColorB  8,9,10 - ColorC 要么 一条线链接路径: 0,1,2,3,4,0 - lineA 0,5,6,7,0- lineB 0,8,9,10,0 - lineC

我试过这段代码

Xsolution = []
Ysolution = []

for i in range(len(list)): 
    Xsolution.append(X[list[i]])
    Ysolution.append(Y[list[i]])
    if list[i] == 0 :
         plt.scatter(Xsolution, Ysolution, color=random_color())
         Xsolution = []
         Ysolution = []

我需要一个每次list [i]为0时生成随机颜色的函数

1 个答案:

答案 0 :(得分:0)

import matplotlib.pyplot as plt
from random import randint
import numpy as np

Xsolution = []
Ysolution = []

alist = #list of values

for i in range(len(alist)): 
    Xsolution.append(X[alist[i]])
    Ysolution.append(Y[alist[i]])

labels = range(1,len(alist)+1)
i = 0
fig = plt.figure()
ax = fig.add_subplot(111)
for x,y in zip(Xsolution,Ysolution):
    ax.scatter(x,y,label=labels[i])
    if # reached the zero element
        i = i + 1 #change the label

#Now this is actually the code that you need, an easy fix to cut and paste.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
     j1.set_color(colorst[t])


plt.show()

我从网上传出这个并将其固定到我需要的地方