How do I plot a function curve in R?

Plotting a function curve in R is relatively straightforward. To plot a function curve, you need to first specify the function, which can be done using the plot() function. After specifying the function, you can provide the x- and y-values and use the type argument to specify the type of plot you want to create, such as a line, scatter, or bar plot. Finally, you can use the add argument to specify additional plotting parameters, such as line color, line thickness, and point size, to customize your plot.


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 .

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

x