R code and corresponding plot 3