In this document, I will demonstrate two ways of producing captions. The first uses the gridExtra
package to draw it right on the plot, and the second uses R Markdown’s captioning features. The first approach is manual and a bit fussy, while the second approach is simpler but less customizable.
The gridExtra
package lets you combine multiple plots into a single image (separate from any ggplot2
faceting) and add annotations. Each piece of the overall plot is called a grob. You can add ggplot
grobs as well as text. Here is an example where we add a “master” title and a caption below.
# install.packages("gridExtra")
library(ggplot2)
library(gridExtra)
library(grid)
# store your plots as objects
plot_1 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point() +
ggtitle("The left cars plot")
plot_2 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_line() +
ggtitle("The right cars plot")
# put side-by-side
grid.arrange(plot_1, plot_2, ncol=2,
top = textGrob("Figure 1: Both the plots are here",
x = 0, # starts far left
y = 0.5, # experiment with
# vertical placement
just = "left", # left-aligned,
gp = gpar(fontsize = 18) # bigger font
),
bottom = textGrob("Note: these plots really show the same information, except the one on the right connects\nthe dots in a way that is probably misleading since these represent independent observations.",
x = 0,
y = 0.5,
just = "left"))