How to Plot Functions in R

Channel:
Subscribers:
53,300
Published on ● Video Link: https://www.youtube.com/watch?v=x7OXp3KvynU



Category:
Guide
Duration: 2:36
28,926 views
325


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.







Tags:
plot functions in r
draw functions in r
plot curves in r
draw curves in r
r function plotting
r function drawing
r plotting basics
plot arbitrary functions
r function plot
graph lines in r
r draw functions
plot mathmatical functions in r
plot math functions in r