Skip to content

Instantly share code, notes, and snippets.

@chelseaparlett
Created January 24, 2023 01:23
Show Gist options
  • Save chelseaparlett/b1c69aacab8322e216987ecc23427d13 to your computer and use it in GitHub Desktop.
Save chelseaparlett/b1c69aacab8322e216987ecc23427d13 to your computer and use it in GitHub Desktop.
library(tidyverse)
library(MASS)
# plot e^x
x <- -5:5
dat <- data.frame(x,y=exp(x))
f <- function(x) exp(x)
p <- ggplot(dat, aes(x,y)) +
stat_function(fun=f, colour="red") +
theme_minimal() +
labs(title = "e^x") +
ylim(c(0,150))
# plot taylor polynomials
# 0
f <- function(x) 1
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 0-degree Taylor Polynomial")
# 1
f <- function(x) 1 + x
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 1-degree Taylor Polynomial")
# 2
f <- function(x) 1 + x + (x**2)/factorial(2)
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 2-degree Taylor Polynomial")
# 3
f <- function(x) 1 + x + (x**2)/factorial(2) + (x**3)/factorial(3)
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 3-degree Taylor Polynomial")
# 4
f <- function(x) 1 + x + (x**2)/factorial(2) + (x**3)/factorial(3) +
(x**4)/factorial(4)
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 4-degree Taylor Polynomial")
# 5
f <- function(x) 1 + x + (x**2)/factorial(2) + (x**3)/factorial(3) +
(x**4)/factorial(4) + (x**5)/factorial(5)
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 5-degree Taylor Polynomial")
# 6
f <- function(x) 1 + x + (x**2)/factorial(2) + (x**3)/factorial(3) +
(x**4)/factorial(4) + (x**5)/factorial(5) + (x**6)/factorial(6)
p + stat_function(fun = f, color = "blue") +
labs(title = "e^x approximated by a 6-degree Taylor Polynomial")
# background image
ggplot(dat, aes(x,y)) +
theme_void()
ylim(c(0,150))
ggsave(paste0(home, "background.png"),
height = 4, width = 6, units = "in", bg = "white")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment