简体   繁体   English

R图例颜色未显示,随机图颜色

[英]R plot legend colors not showing, random plot colors

I am working with a generic plot fxn that does not know how many lines it will plot until it's completed plotting. 我正在使用通用绘图fxn,在完成绘图之前,该绘图不知道它将绘制多少行。 The data is plotting just fine, though when I try to create the legend, I'm not getting the colors. 数据绘制得很好,尽管当我尝试创建图例时,我没有得到颜色。

Since the number of lines is unknown I am generating colors for the lines at random; 由于行数是未知的,所以我随机地为行生成颜色。 BUT, I am storing the color in a array/vector. 但是,我将颜色存储在数组/向量中。

From my code: I understand this is not easily reproduced, but it is not easily dumbed down, as I've gotten to the point of dumbed down and not able to find the problem... 从我的代码中:我知道这不容易复制,但是不容易复制,因为我已经达到了愚蠢的地步,无法发现问题...

# plot blank plot
plot(1, type="n", xlab="time elapsed [sec]", ylab="Memory Used [MB]", ylim=c(ymin,ymax),   
  xlim=c(xmin,xmax))

 # LOOOOP over column 2 (node)
for(i in 1: length(col2))
{
  if(col2[i] == compareNode)
  {
    #print(paste0("count: ", count))

    # x = time value, y = memory used value for node: compareNode
    x[count] = col1[i]
    y[count] = (col87[i] - col85[i])/1024
    count = count + 1
  }
  else
  {
    # Plot 
    colTest <- sample(colors(), 1)
    mycols <- c(mycols,colTest)
    lines(x, y, col=colTest )

    NODES[nodeCount] = col2[i]
    nodeCount = nodeCount + 1
    # Resets
    compareNode = col2[i]
    x = c()
    y = c()
    count = 1

  }
}

# Plot final line
colTest <- sample(colors(),1)
mycols <- c(mycols,colTest)
lines(x, y, col=colTest)
#print(colors)
legend("topleft", title="LDMS: Memory Used", legend = NODES, col=mycols )
garbage <- dev.off()

Trying for a better example here: 在这里尝试一个更好的例子:

loop x times:
  color <- sample(colors(),1)
  mycols <- c(mycosl,color)
  lines(x,y,col=color)
done
lines(x,y,col=color)   # plots last set of data
legend("topright", title="title", legend=NODES, col=mycols)

Staying as close as possible to your code, and assuming we indeed don't know how many lines we're going to plot: 尽可能接近您的代码,并假设我们确实不知道要绘制多少行:

mycols <- c();
while (sample(1:100, 1) != 14) {
  col <- sample(colors(), 1);
  mycols <- c(mycols, col);
  ##lines(..., col=col) # plot line
}
legend("topleft", title="LDMS: Memory Used", legend = NODES, col=mycols, lty=1)

Better yet, don't just resample 1 element from colors(), but randomize the output of colors() once and then just iterate over it. 更好的是,不要只是从colors()重新采样1个元素,而是随机对colors()的输出进行一次,然后对其进行迭代。 This will make sure you don't inadvertently reuse any colors. 这样可以确保您不会无意间重复使用任何颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM