同一函数的两个版本在stat_function中的行为不同

时间:2016-12-07 22:44:11

标签: r ggplot2

假设我想使用以下数据绘制函数:

my_data <- data.frame("x" = rep(1:4, times = 20))
my_coef <- c(78, -71, 43, -7)

编写函数有两种不同的方法:

fun_version1 <- function(x) {
    my_coef[1] + my_coef[2]*x + my_coef[3]*(x^2) + my_coef[4]*(x^3)
}


fun_version2 <- function(x){
    sum(as.vector(outer(x, 0:3, FUN="^")) * my_coef)
}

尽管两个函数在插入值时返回完全相同的结果,但只有fun_version1在ggplot中看起来很好:

library(ggplot2)    
# plot using version 1 of the function
        ggplot(data = my_data, aes(x = x)) + 
            stat_function(fun = fun_version1, aes(col = "1"), lwd = 1.2)

# plot using version 2 of the function
        ggplot(data = my_data, aes(x = x)) + 
            stat_function(fun = fun_version2, aes(col = "1"), lwd = 1.2)

我需要以 fun_version2 的形式绘制函数。有没有办法在ggplot函数stat_function()中使用此版本或某种解决方法?

0 个答案:

没有答案
相关问题