2013-08-28 71 views
1

我不知道如何在ggplot2中的curve()函数中复制add = TRUE参数?在ggplot2中覆盖很多曲线

假设我有这样的情节

 testfn<-function(x,a){ 
     sin(x-a) 
    } 

    for(i in 1:10){ 
     curve(testfn(x,i),add=TRUE,xlim=c(-5,5)) 
    } 

如何在GGPLOT2做到这一点,而无需手动添加10 + stat_function()秒?

感谢

回答

4

创建使用调用到stat_function列表lapply

library(ggplot2) 
# the base plot (with x limits) 
xlim <- c(-5,5) 
baseplot <- ggplot(data.frame(x = xlim), aes(x=x)) 

# the function 
testfn <- function(x,a){sin(x-a)} 
# a list of 10 calls (a = 1,...10) 
list_fn <- lapply(seq_len(10), function(a){ 
    stat_function(fun = testfn, args = list(a=a)) 
}) 
# the plot 
baseplot + list_fn 

enter image description here