ggplot在for循环中添加水平线

时间:2018-03-12 20:38:53

标签: r ggplot2

我试图根据向量中给出的截距向ggplot添加水平线。由于此向量的长度会有所不同,并且此向量不一定遵循任何序列,因此我将其置于for循环中,但我只能看到最后一行添加。 当我添加没有for循环(这意味着固定的矢量大小)时,我得到了我想要的情节。

library(ggplot2)
library(viridis)
dat = data.frame(x=runif(10), y=runif(10))
lines = c(0.1,0.2,0.3)
nlines = length(lines)
vpal = viridis(nlines,end=0.9)

## I only see the last line added:
p <- ggplot(dat,aes(x,y)) + geom_point()
for(i in 1:nlines){
    p <- p + geom_hline(aes(yintercept=lines[i]), colour=vpal[i], linetype="dashed")
}

## I see all lines:
p <- ggplot(dat,aes(x,y)) + geom_point()
p <- p + geom_hline(aes(yintercept=lines[1]), colour=vpal[1], linetype="dashed")
p <- p + geom_hline(aes(yintercept=lines[2]), colour=vpal[2], linetype="dashed")   
p <- p + geom_hline(aes(yintercept=lines[3]), colour=vpal[3], linetype="dashed")

也许我错过了一些明显的东西,但是如何在ggplot中添加可变数量的行?谢谢!

0 个答案:

没有答案