How to Plot an Equation in R (With Examples)


You can use the following basic syntax to plot an equation or function in R:

Method 1: Use Base R

curve(2*x^2+5, from=1, to=50, , xlab="x", ylab="y")

Method 2: Use ggplot2

library(ggplot2)

#define equation
my_equation <- function(x){2*x^2+5}

#plot equation
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=my_equation)

Both of these particular examples plot the equation y = 2x2 + 5.

The following examples show how to use each method in practice.

Example 1: Plot Equation in Base R

Suppose you’d like to plot the following equation:

y = 2x2 + 5

You can use the following syntax in base R to do so:

curve(2*x^2+5, from=1, to=50, , xlab="x", ylab="y")

This produces the following plot:

plot equation in R

If you’d like to plot points instead, simply specify type=”p” in the curve() function:

curve(2*x^2+5, from=1, to=50, , xlab="x", ylab="y", type="p")

This produces the following plot:

Example 2: Plot Equation in ggplot2

Suppose you’d like to plot the following equation:

y = 2x2 + 5

You can use the following syntax in ggplot2 to do so:

library(ggplot2)

#define equation
my_equation <- function(x){2*x^2+5}

#plot equation
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=my_equation)

This produces the following plot:

Notice that this plot matches the one we created in the previous example in base R.

Note: To plot a different equation, simply change the values defined for the my_equation variable.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Add a Regression Equation to a Plot in R
How to Create an Interaction Plot in R
How to Create a Residual Plot in R

Leave a Reply

Your email address will not be published. Required fields are marked *