The problem is that the parameter values of ggplot for the most part are lazily evaulated. The values aren't actually evaluated until the plot is drawn. Since your function uses global variables, those values aren't resolved till plot time and at the time of the plot they will only have one value, not two different values. You can change this by creating a function generator. For example
f_gen <- function(alpha1, delta1) {
force(c(alpha1, delta1))
function(x){
2*(1+delta1*x^2)*dnorm(x)*pnorm(alpha1*x)/(1+delta1)
}}
alpha1 <- 0
delta1 <- 0
group1 <- paste("alpha=",alpha1,", delta=",delta1)
p9 <- ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
stat_function(fun = f_gen(alpha1,delta1), aes(colour = group1))
alpha1 <- 0
delta1 <- 6
group2 <- paste("alpha=",alpha1,", delta=",delta1)
p9 <- p9 +
stat_function(fun = f_gen(alpha1,delta1), aes(colour = group2))
p9
Here fgen is a function that returns a function with the parameters you desire.
You might even simplify that to
f_gen <- function(alpha1, delta1) {
force(c(alpha1, delta1))
function(x){
2*(1+delta1*x^2)*dnorm(x)*pnorm(alpha1*x)/(1+delta1)
}}
gname <- function(alpha1, delta1) paste("alpha=",alpha1,", delta=",delta1)
ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
stat_function(fun = f_gen(0,0), aes(colour = gname(0,0))) +
stat_function(fun = f_gen(0,6), aes(colour = gname(0,6))) +
labs(color="Params")