【问题标题】:How to use an if/else statement to plot different colored lines within a plotting for-loop (in R)如何使用 if/else 语句在绘图 for 循环中绘制不同颜色的线(在 R 中)
【发布时间】:2019-03-28 20:33:01
【问题描述】:

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

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

这是我创建的用于绘制 38 行的 for 循环,每行对应于每个样本。在这种情况下,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 种不同的颜色,而不仅仅是两种。

谢谢!

【问题讨论】:

  • 您能否发布一个minimal reproducible example 您的数据(最好是一个只有 2 或 3 行不同行的小示例),以便我们重现并尝试解决您的问题?您可以使用dput 将 R 对象输出为可以粘贴到问题中的文本

标签: r for-loop if-statement plot


【解决方案1】:

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')
  }
}

【讨论】:

  • 成功了!非常感谢您的快速回复。展望未来,如果您有任何建议,我仍然想根据几个不同的箱子(比如 0-16、16-20 和 20-30 年)绘制不同的颜色。
  • 如果您不关心哪种颜色映射到哪个 bin ggplot2 将是最简单的
猜你喜欢
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多