Search code examples
rplotcurveexponential

Add exponential curve to plot


I am looking to add a curve to my plot to show an exponential decrease over time. Ive plotted two small sets of data with the basic plot() function and just for clarity I wanted to add a smoothed line. The data points for the two datasets are

1.00000 0.37360 0.27688 0.22992 0.17512 0.13768 0.08048
1.00000000 0.44283122 0.30871143 0.23647913 0.22586207 0.09800363 0.06206897

with the x values showing the decay over time (0,1,2,3,4,5,6)

plot


Solution

  • I like to use ggplot2 as it makes adding lines from fitted models so simple.

    Without to much to go on the following may help you out....

    #prepare the data
    y <- c(1.00000, 0.37360, 0.27688, 0.22992, 0.17512, 0.13768, 0.08048,
       1.00000000, 0.44283122, 0.30871143, 0.23647913, 0.22586207, 0.09800363, 0.06206897)
    x <- c(0,1,2,3,4,5,6,0,1,2,3,4,5,6)
    z <- c(1,1,1,1,1,1,1,0,0,0,0,0,0,0)
    
    
    dat <- as.data.frame(cbind(x,y,z))
    
    #load the library
    library(ggplot2)
    
    #plot the data
    ggplot(data=dat,aes(x=x,y=y))+
    
    #add Points with different shapes depending on factor z
    geom_point(aes(shape=factor(z)))+
    
    #Add line using non-linear regreassion
    stat_smooth(method="nls",formula =  y~a*exp(-x*b),method.args=list(start=c(a=2,b=2)),se=F,color="red")+
    
    #add line using linear regression
    stat_smooth(method="lm",formula =  y~exp(-x),se=F,color="blue")