Completed the R code for plot 4