How to plot a function

Use the stat_function

library(ggplot2, quietly=T)
ggplot(data.frame(z=c(-4,4)), aes(x=z)) + stat_function(fun = dnorm, color="steelblue")

May add arguments

ggplot(data.frame(z=c(0,20)), aes(x=z)) + stat_function(fun = dnorm, args=list(mean=10, sd=5), color="steelblue")

Define your own function. If you use if in the function, you must vectorize it, otherwise you get errors

rw <- function(xvar) {1/(1+exp(- xvar+10))}
ggplot(data.frame(x=c(0,20)), aes(x=x)) + stat_function(fun = rw, n=200) #pass large n to smooth

# Return of annual saving as, rate , years
cg <- function(amount, rate, years) {return(amount*((1+rate)^years))}
late <- function(amount, rate, delay, years){ifelse(years<delay, 0, amount*((1+rate)^(years-delay)))}
ggplot(data.frame(years=c(0:50)), aes(x=years)) + stat_function(fun=cg, args=list(amount=5500, rate=0.04 ), color="steelblue", size=2) +  stat_function(fun=late, args=list(amount=10000, rate=0.04, delay=30), color="firebrick", size=2)