Push the knit button!

If the image is not showing up, first open the corresponding solution file (in the same location as this file) and knit.

library(ggplot2)
library(grid)

Exercise 2.1: Line of best fit

  • Change the best line of fit below to a red color using grid only
ggplot(cars, aes(speed, dist)) + 
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE, formula = y ~ x) + 
  ggtitle("Line of best fit")

grid.force()

grid.ls()
## layout
##   background.1-9-12-1
##   panel.7-5-7-5
##     grill.gTree.16382
##       panel.background..rect.16373
##       panel.grid.minor.y..polyline.16375
##       panel.grid.minor.x..polyline.16377
##       panel.grid.major.y..polyline.16379
##       panel.grid.major.x..polyline.16381
##     NULL
##     geom_point.points.16366
##     geom_smooth.gTree.16369
##       GRID.polyline.16367
##     NULL
##     panel.border..zeroGrob.16370
##   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.16389
##       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.16385
##   xlab-t.5-5-5-5
##   xlab-b.9-5-9-5
##     GRID.text.16393
##   ylab-l.7-3-7-3
##     GRID.text.16396
##   ylab-r.7-7-7-7
##   subtitle.4-5-4-5
##   title.3-5-3-5
##     GRID.text.16399
##   caption.10-5-10-5
##   tag.2-2-2-2
  • Draw a line using grid that points from the title to the line of best fit in the above plot

Exercise 2.2: Side-by-side plots with annotations

  • Draw the plots below side-by-side such that the dimension of the right plot is half of the one on the left using grid (some of the code has been written for you )
  • Then draw a red circle around the right plot
g1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() + 
  ggtitle("Sepal")

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

g1 

g2

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)
...