forked from rstudio-education/stat545
-
Notifications
You must be signed in to change notification settings - Fork 0
/
29_multiple-plots.Rmd
122 lines (88 loc) · 4.18 KB
/
29_multiple-plots.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# Multiple plots on a page {#multiple-plots}
```{r include = FALSE}
source("common.R")
```
<!--Original content: https://stat545.com/block020_multiple-plots-on-a-page.html-->
<!--TODO: add patchwork package here?-->
## Faceting is not a panacea
Faceting is useful for constructing an array of similar plots where each panel corresponds to a level of a factor or a combination of levels from multiple factors. Pragmatic reshaping can make lots of graphing problems have this "look". But this does not cover the entire spectrum of multi-plot needs in the real world. Sometimes you need to get more than one plot on a virtual page and the plots are rather disconnected. How do you do that?
## Meet the gridExtra package
Under the hood, ggplot2 uses the grid package to create figures. The gridExtra packages provides some extra goodies and we will draw on them to place multiple ggplot2 plots on a single virtual page.
You may need to install gridExtra and you will certainly need to load it.
```{r}
# install.packages("gridExtra")
library(gridExtra)
```
## Load gapminder and ggplot2
```{r}
library(gapminder)
library(ggplot2)
```
## Use the `arrangeGrob()` function and friends
Store the constituent plots to plot objects and then pass them to `grid.arrange()` or `arrangeGrob()`.
```{r arrangeGrob-demo}
p_dens <- ggplot(gapminder, aes(x = gdpPercap)) + geom_density() + scale_x_log10() +
theme(axis.text.x = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank())
p_scatter <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
geom_point() + scale_x_log10()
#p_both <- arrangeGrob(p_dens, p_scatter, nrow = 2, heights = c(0.35, 0.65))
#print(p_both)
grid.arrange(p_dens, p_scatter, nrow = 2, heights = c(0.35, 0.65))
```
You can find other examples of this workflow in the [R Graph Catalog][r-graph-catalog-github].
## Use the `multiplot()` function
In the [Graphs](http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/) chapter of his [Cookbook for R][cookbook-for-r], Winston Chang uses the grid package to define the `multiplot()` function:
```{r chang-cookbook, eval = FALSE}
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols: Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
```
Assuming that the plot objects `p1`, `p2`, `p3`, and `p4` are pre-defined, call the function like this:
```{r eval = FALSE}
multiplot(p1, p2, p3, p4, cols = 2)
```
Visit [Multiple graphs on one page (ggplot2)][cookbook-for-r-multigraphs] to see a complete worked example.
## Use the cowplot package
The cowplot package ([CRAN][cowplot-cran]; [GitHub][cowplot-github]) does (at least) two things:
* Provides a publication-ready theme for ggplot2.
* Helps combine multiple plots into one figure.
Check out [the vignette][cowplot-vignette] to see it in action.
```{r links, child="links.md"}
```