How to Plot Functions in R @DataDaft
How to Plot Functions in R  @DataDaft
Uploaded November 2019 | Updated November 2026, 1 hour ago
R allows for arbitrary function plotting using the curve() function in base R and stat_function() in the ggplot2 package. This can be useful for comparing functions or adding curves to other plots like scatterplots.

Code used in this code clip:

f1 <- function(x){
return( x^2 - x )
}

# Drawing a function curve in base R
curve(expr = f1, from = -3, to = 3)

library(tidyverse)

f2 <- function(x){
ifelse(x < 0, -x, x)
}

# Drawing a function in ggplot2
ggplot(data.frame(x = c(-5, 5)), aes(x = x)) +
stat_function(fun = f2)

# Draw multiple functions function in one plot
four_curves <- ggplot(data.frame(x = c(-5, 5)), aes(x = x)) +
stat_function(fun = exp, color="red", lwd = 1) +
stat_function(fun = function(x){x^3}, color="blue", lwd = 1) +
stat_function(fun = function(x){4*x^2}, color="green", lwd = 1) +
stat_function(fun = function(x){10*x}, color="black", lwd = 1) +
annotate(geom="text", label = "Exponential", x = -4, y = 5, size =5) +
annotate(geom="text", label = "Quadratic", x = -4, y = 95, size =5) +
annotate(geom="text", label = "Cubic", x = -4, y = -90, size =5) +
annotate(geom="text", label = "Linear", x = -4, y = -32, size =5)

four_curves


Code Clips are basic code explanations in 3 minutes or less. They are intended to be short reference guides that provide quick breakdowns and copy/paste access to code needed to accomplish common data science tasks. Think Stack Overflow with a video explanation.


* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above may not be exactly the same as the code shown in the video! For R that means I may use = for assignment and the special Unicode large < and > symbols in place of the standard sized ones for dplyr pipes and comparisons. These special symbols should work as expected for R code on Windows, but may need to be replaced with standard greater than and less than symbols for other operating systems.
How to Plot Functions in RPython Programming Practice: LeetCode #1   Two SumOne Piece Bounties Over Time (1 Second = 4 Chapters)How to Remove a Column From a Data Frame in Pandas (Python)How to Make Violin Plots in RThe Meta MOOC: Getting the Most out of Online Learningdplyr: separate and unite
DataDaft |

How to Plot Functions in R

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER