# Graph a function with ggplot2

Hello!

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)
``````

Anyone could show me how to do that?

Thanks a lot!

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
#>  28.22464
#>
#> \$objective
#>  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()
`````` Created on 2022-06-06 by the reprex package (v2.0.1)

1 Like

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?

``````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

OPT <- optimize(f, c(0, 51), maximum = T)
OPT_DF <- data.frame(x = OPT\$maximum, y = OPT\$objective,
Label = paste(round(OPT\$maximum,2),
round(OPT\$objective,2), sep = ","))
library(ggplot2)
ggplot(data.frame(x=0:51), aes(x=x)) +
stat_function(fun=f) +
geom_point(aes(x=x, y = y), data = OPT_DF) +
geom_text(aes(x = x, y = y+0.02, label = Label), data = OPT_DF, vjust = 0)
`````` Created on 2022-06-07 by the reprex package (v2.0.1)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.