繁体   English   中英

如何使用if / else语句在绘制for循环中绘制不同的彩色线(在R中)

[英]How to use an if/else statement to plot different colored lines within a plotting for-loop (in R)

我创建了一个for循环以绘制38条线(这是我的矩阵的结果result.summary.evap的行,并对应于38个样本)。 我想根据与每个样本有关的特征,使这些线条具有不同的颜色:年龄。 我可以在输入矩阵中输入年龄:surp.data $ Age_ka。

但是,我要遍历的矩阵(results.summary.evap)没有样本年龄或样本名称,尽管对于surp.data和result.summary.evap每个样本都应位于同一行中。

这是我创建的for循环,用于绘制38条线,每条线对应一个样本。 在这种情况下,results.summary.evap是我要绘制的内容,并且此矩阵是根据surp.data输入文件中的信息得出的。

par(mfrow=c(3,1)) 
par(mar=c(3, 4, 2, 0.5))
plot(NA,NA,xlim=c(0,10),ylim=c(0,2500), ylab = "Evaporation (mm/yr)", xlab = "Relative Humidity")
for(i in 1:range){
  lines(rh.sens,results.summary.evap[i,])
}
```


I'd like to plot lines in different colors based on the age associated with each sample. I tried to incorporate an if/else statement into the loop, that would plot in a different color if the corresponding sample age was greater that 20 in the input file. 


```
for(i in 1:range){
  if surp.data$Age_ka[i]>20 {
lines(rh.sens,results.summary.evap[i,], col = 'red')
} else {
  lines(rh.sens,results.summary.evap[i,], col = 'black')
  }
}

此for循环不会运行(由于括号问题)。 我不确定如果从根本上错了,或者我只是想念某个地方的括号,该怎么做。 我也不确定如何使它更可靠。 例如,根据年龄范围绘制6-8种不同的颜色,而不仅仅是两种。

谢谢!

您在if语句周围缺少括号

for(i in 1:range){
  if(surp.data$Age_ka[i]>20){
    lines(rh.sens,results.summary.evap[i,], col = 'red')
  } else {
    lines(rh.sens,results.summary.evap[i,], col = 'black')
  }
}

暂无
暂无

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

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