How to Plot a Function Curve in R (With Example)


You can use the following methods to plot a function curve in R:

Method 1: Use Base R

curve(x^3, from=1, to=50, xlab='x', ylab='y') 

Method 2: Use ggplot2

library(ggplot2)

df <- data.frame(x=c(1, 100))
eq = function(x){x^3}

#plot curve in ggplot2
ggplot(data=df, aes(x=x)) + 
  stat_function(fun=eq)

Both methods will produce a plot that shows the curve of the function y = x3.

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

Example 1: Plot Function Curve Using Base R

The following code shows how to plot the curve of the function y = x3 using the curve() function from base R:

#plot curve using x-axis range of 1 to 50
curve(x^3, from=1, to=50, xlab='x', ylab='y')

plot function curve in base R

Note that you can use the following arguments to modify the appearance of the curve:

  • lwd: Line width
  • col: Line color
  • lty: Line style

The following code shows how to use these arguments in practice:

#plot curve using x-axis range of 1 to 50
curve(x^3, from=1, to=50, xlab='x', ylab='y', lwd=3, col='red', lty='dashed'))

Feel free to play around with the values for these arguments to create the exact curve you’d like.

Example 2: Plot Function Curve Using ggplot2

The following code shows how to plot the curve of the function y = x3 using the stat_function() function from ggplot2:

library(ggplot2)

#define data frame
df <- data.frame(x=c(1, 100))

#define function 
eq = function(x){x^3}

#plot curve in ggplot2
ggplot(data=df, aes(x=x)) + 
  stat_function(fun=eq)

plot function curve in ggplot2

You can also use the lwd, col, and lty functions within the stat_function() function to modify the appearance of the curve:

library(ggplot2)

#define data frame
df <- data.frame(x=c(1, 100))

#define function 
eq = function(x){x^3}

#plot curve in ggplot2 with custom appearance
ggplot(data=df, aes(x=x)) + 
  stat_function(fun=eq, lwd=2, col='red', lty='dashed')

Note: You can find the complete documentation for the ggplot2 stat_function() function here.

Additional Resources

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

How to Change Legend Position in R Plots
How to Use bty to Change Chart Box Styles in R
How to Use cex to Change Size of Plot Elements in R

Featured Posts

Leave a Reply

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