Scatterplot With Trend Line

Want to learn more? I recommend working through: R for Data Science, R Cookbook, and R Graphics Cookbook.

# load the gcookbook package for the data
library(gcookbook)

# load the ggplot2 package
library(ggplot2)

# load plyr package
library(plyr)

# reset the graphing device
dev.off()
null device
          1
# create the scatterplot
sps <- ggplot(heightweight, aes(x = ageYear, y = heightIn, colour = sex)) +
  geom_point() +
  scale_colour_brewer(palette = "Set1")
# create a scatterplot with loess smoothing
sps + geom_smooth()
geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.

png

# create a scatterplot with lm (straight line) trend line
sps + geom_smooth(method=lm, se=FALSE, fullrange=TRUE)

png