在循环中使用 par(new=T):不同的颜色?

Using par(new=T) in loops: different colors?

我想使用 par(new = TRUE) 绘制我的绘图,这些绘图是在另一个循环中生成的。 但是我如何确保每个新情节都有另一种颜色? 现在全黑叠加了,分不清情节了:

for(i in names(extensor_raw[2:9])){
  # Coerce a data.frame into an 'emg' object
  x <- as.emg(extensor_raw[i], samplingrate = 1000, units = "mV")  ##do this for every channel
  
  # Compute the rectified signal
  x_rect <- rectification(x)
  
  # Filter the rectified signal
  y <- lowpass(x_rect, cutoff = 100)
  
  # plot the original channel, the filtered channel and the LE-envelope
  plot(y, main = paste("LE-envelope"))
  par(new = TRUE) 
}

我试图实现以下内容:我试图包括 col = rainbow(9)[i],但这只给我一个空白图:

plot(y, main = paste("LE-envelope") , col=rainbow(9)[i])
par(new = TRUE) 

正如评论中所要求的那样,我使用了dput(y)(不确定该职位是否正确:

for(i in names(extensor_raw[2:9])){
  # Coerce a data.frame into an 'emg' object
  x <- as.emg(extensor_raw[i], samplingrate = 1000, units = "mV")  ##do this for every channel
  
  # Compute the rectified signal
  x_rect <- rectification(x)
  
  # Filter the rectified signal
  y <- lowpass(x_rect, cutoff = 50)

  # plot the original channel, the filtered channel and the 
  # LE-envelope
  plot(y, main = paste("LE-envelope extensor") , col=rainbow(9)[i])
  par(new=T) 
}
    
dput(y)

结果是:

plot(y, main = paste("LE-envelope", i), col=rainbow(9)[i]) 

您定义了 for 循环以遍历 names(extensor_raw)。这意味着 i 将是每个循环中的一个字符。但是,要定义任何颜色,您都需要一个数值。解决方案是迭代一个整数序列:

seq_along(names(extensor_raw[2:9]))
# [1] 1 2 3 4 5 6 7 8

这样,col = rainbow(9)[i] 就可以了,例如:

i <- 5
rainbow(9)[i]
# [1] "#00FFAA"

我还修改了代码以使用单个 plot 调用。从那里,我们只需添加带有 lines 函数的行。我用 if-else 语句来做到这一点。

此外,我们需要正确定义 y 范围。所以,我们可以这样做:

y_range <- c(0, max(extensor_raw[2:9]))

然后我们可以在plot中使用y_range

完整代码:

for(i in seq_along(names(extensor_raw[2:9]))) {
  x <- as.emg(extensor_raw[i], samplingrate = 1000, units = "mV")  ##do this for every channel
  x_rect <- rectification(x)
  y <- lowpass(x_rect, cutoff = 100)

  if (i == 1) {
    plot(y, main = "LE-envelope", col = rainbow(9)[i], ylim = y_range)
  } else {
    lines(y, col = rainbow(9)[i])
  }
}