I would like to graph a function with ggplot2, but I'm not sure how to do that (still beginning in R). I did the following code, but this doesn't work:
f <- function(x, a, b, c) a + b*x - c*x^2
formals(f)$a <- 0.39384
formals(f)$b <- 0.03895
formals(f)$c <- 0.00069
optimize(f, c(0, 51),
maximum = T)
ggplot(data.frame(x=c(0, 51), aes(x=x, a=a, b=b, c=c)) +
stat_function(fun=f)
Here is a modified version of what you were doing and another method.
f <- function(x, a, b, c) a + b*x - c*x^2
formals(f)$a <- 0.39384
formals(f)$b <- 0.03895
formals(f)$c <- 0.00069
optimize(f, c(0, 51),
maximum = T)
#> $maximum
#> [1] 28.22464
#>
#> $objective
#> [1] 0.9435148
library(ggplot2)
ggplot(data.frame(x=0:51), aes(x=x)) +
stat_function(fun=f)
#Another method, without using formals()
f <- function(x, a, b, c) a + b*x - c*x^2
DF <- data.frame(x = 1:51, y = f(1:51, a = 0.39384, b= 0.03895, c = 0.00069))
ggplot(DF,aes(x,y)) + geom_line()
Thanks, that's perfect! Would there also be a way to add a point at the maximum of the function that would show the coordinates of the maximum from the optimized() function?