library(ggplot2)
library(grid)

Exercise 2.1: Line of best fit

ggplot(cars, aes(speed, dist)) + 
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE, formula = y ~ x)

grid.force()

grid.ls()
## layout
##   background.1-9-12-1
##   panel.7-5-7-5
##     grill.gTree.28
##       panel.background..rect.19
##       panel.grid.minor.y..polyline.21
##       panel.grid.minor.x..polyline.23
##       panel.grid.major.y..polyline.25
##       panel.grid.major.x..polyline.27
##     NULL
##     geom_point.points.12
##     geom_smooth.gTree.15
##       GRID.polyline.13
##     NULL
##     panel.border..zeroGrob.16
##   spacer.8-6-8-6
##   spacer.8-4-8-4
##   spacer.6-6-6-6
##   spacer.6-4-6-4
##   axis-t.6-5-6-5
##   axis-l.7-4-7-4
##     NULL
##     axis
##       axis.1-1-1-1
##         GRID.text.36
##       axis.1-2-1-2
##   axis-r.7-6-7-6
##   axis-b.8-5-8-5
##     NULL
##     axis
##       axis.1-1-1-1
##       axis.2-1-2-1
##         GRID.text.31
##   xlab-t.5-5-5-5
##   xlab-b.9-5-9-5
##     GRID.text.40
##   ylab-l.7-3-7-3
##     GRID.text.44
##   ylab-r.7-7-7-7
##   subtitle.4-5-4-5
##   title.3-5-3-5
##   caption.10-5-10-5
##   tag.2-2-2-2
grid.edit(grid.grep("GRID.polyline", grep = TRUE), gp = gpar(col = "red"))

ggplot(cars, aes(speed, dist)) + 
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE, formula = y ~ x) +
  ggtitle("Best line of fit")
grid.segments(0.3, 0.92, 
              0.4, 0.35,
              arrow = arrow(angle = 10, type = "closed"),
              gp = gpar(fill = "black"))

Exercise 2.2: Side-by-side plots with annotations

g1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() + 
  ggtitle("Sepal")

g2 <- ggplot(iris, aes(Petal.Length, Petal.Width)) +
  geom_point() + 
  ggtitle("Petal")

gr1 <- ggplot_gtable(ggplot_build(g1))
gr2 <- ggplot_gtable(ggplot_build(g2))
vp1 <- viewport(width = 0.5, height = 0.5, x = 0.25)
vp2 <- viewport(width = 0.25, height = 0.25, x = 0.75)
pushViewport(vp1)
grid.draw(gr1)
popViewport()
pushViewport(vp2)
grid.draw(gr2)
grid.circle(gp = gpar(col = "red", fill = "transparent"), r = 1)