4 C
London
Friday, December 20, 2024
HomeRDescriptive Statistics in RHow to Plot an Equation in R (With Examples)

How to Plot an Equation in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories