1 Layer-by-layer ggplot()

require(ggplot2)
require(gridExtra)
require(tidyr)
?mpg
require(knitr)
kable(head(mpg))
manufacturer model displ year cyl trans drv cty hwy fl class
audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
audi a4 2.0 2008 4 auto(av) f 21 30 p compact
audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
audi a4 2.8 1999 6 manual(m5) f 18 26 p compact

The mpg (miles-per-gallon) dataset, collected by http://fueleconomy.gov, can be loaded from the ggplot2 package. It contains popular car models in 1999 and 2008, with following variables:

We would like to explore the relationships of miles-per-gallon (cty and hwy) with other variables.

1.1 Scatterplot by Adding Layers

p0 = ggplot(mpg, aes(x=displ, y=hwy)) # default mapping 
p1 = p0 + geom_point(aes(color=factor(cyl))) + ggtitle("Add geom_point with coloring")
p2 = p1 + geom_smooth(aes(color=factor(cyl)), method="lm") + ggtitle("Add geom_smooth")
p3 = p2 + theme_bw() + ggtitle("Add a theme") 
p4 = p3 + facet_wrap(~year) + ggtitle("Add multipanel facets")
grid.arrange(p1, p2, p3, p4, nrow=2, ncol=2)  # require(gridExtra)