forked from tidyverse/ggplot2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfacet-viewports.r
50 lines (44 loc) · 1.36 KB
/
facet-viewports.r
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
# Assign viewports to a matrix of grobs
#
# Uses the structure (and names) of the matrix of grobs, to automatically
# assign each grob to the appropriate viewport
assign_viewports <- function(grobs) {
make_grid <- function(type) {
data.frame(
type = type,
x = c(row(grobs[[type]])),
y = c(col(grobs[[type]]))
)
}
assign_vp <- function(type, x, y) {
ggname(type, editGrob(grobs[[type]][[x, y]], vp = vp_path(x, y, type)))
}
grid <- ldply(names(grobs), make_grid)
mlply(grid, assign_vp)
}
# Setup matrix of viewports for a layout with given parameters
setup_viewports <- function(type, data, offset = c(0,0), clip = "on") {
rows <- nrow(data)
cols <- ncol(data)
vp <- function(x,y) {
# cat(vp_name(x, y, type), ": ", x + offset[1], ", ", y + offset[2], "\n", sep="")
viewport(
name = vp_name(x, y, type),
layout.pos.row = x + offset[1],
layout.pos.col = y + offset[2],
clip=clip
)
}
pos <- expand.grid(x = seq_len(rows), y= seq_len(cols))
do.call("vpList", mlply(pos, vp))
}
# Calculate viewport path.
# Helps ensure a common naming scheme throughout ggplot.
vp_path <- function(row, col, type) {
vpPath("panels", vp_name(row, col, type))
}
# Compute viewport name.
# Helps ensure a common naming scheme throughout ggplot.
vp_name <- function(row, col, type) {
paste(type, row, col, sep="_")
}