2013-08-28 84 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