使用循环或lapply在ggplot中绘制多个函数曲线

时间:2016-12-08 00:44:13

标签: r ggplot2

假设我有以下数据:

coef <- list(c(47, 2, 0, 0), 
             c(7, 42, -8, 0),
             c(78, -71, 43, -7))

my_data <- data.frame("x" = rep(1:4, times = 20))

cols <- c("1", "2", "3")

我想为对象coef中的每个系数向量绘制一个函数。

但是,使用for循环不起作用。

library(ggplot2)    
g1 <- ggplot(data = my_data, aes(x = x)) 

    for(i in 1:3){
    my_fun <- function(x){
        sum(as.vector(outer(x, 0:3, FUN="^")) * coef[[i]])
    }
    my_fun <- Vectorize(my_fun)
    g1 <- (g1 + stat_function(fun = my_fun, aes(col = cols[i]), lwd = 1.2))

    print(g1)
}

结果应该看起来(不知何故)像这样: enter image description here

有没有办法使用lapply而不是循环?或者我可以修改for循环来解决这个问题吗?

0 个答案:

没有答案
相关问题