Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
To add a linear regression line to a scatter plot, add stat_smooth() and tell it to use method=lm. This instructs it to fit the data
with the lm() (linear model)
function. First we’ll save the base plot object in sp, then we’ll add different components to
it:
library(gcookbook)# For the data set# The base plotsp<-ggplot(heightweight,aes(x=ageYear,y=heightIn))sp+geom_point()+stat_smooth(method=lm)
By default, stat_smooth() also adds a 95%
confidence region for the regression fit. The confidence interval can be
changed by setting level, or it can
be disabled with se=FALSE (Figure 5-18):