我试图获得一个多页二维点阵图,以在多个页面上具有相同的调节布局。垂直排列应该是
CCC
BBB
AAA
每页都有。我知道如何手动执行此操作,但代码很难看,尤其是如果最后一页未完全填充。
在2010年的SO帖子中,我读到这是ggplot2的“在列表中”。
library(lattice)
d = expand.grid(f1 = as.factor(letters[1:10]),
f2 = as.factor(LETTERS[1:3]),
x = 0:10)
d$y = rnorm(nrow(d))
xyplot(y~x|f1+f2,data=d,cex=0.5,pch=16,layout=c(5,3,2))
请注意,所有A都位于第一页,后面是B,后面是最后一页上的B和C.
library(lattice)
library(latticeExtra)
# Note: changed so that it does not fill the three pages
d <- expand.grid(f1 = as.factor(letters[1:8]),
f2 = as.factor(LETTERS[1:3]),
x = 0:10)
d$y <- rnorm(nrow(d))
page <- factor((as.numeric(d$f1) - 1) %/% 5 + 1)
# The second (=last) page has different panel sizes
# Using aspect does not help
for(pg in levels(page)) {
p <- xyplot(y ~ x|f1+f2, data = d[pg == page, ], cex = .5, pch = 16,
layout = c(5, 3))
print(useOuterStrips(p))
}
答案 0 :(得分:3)
假设需要的是两页:
和
然后试试这个:
p <- xyplot(y ~ x | f2:f1, data = d, cex = 0.5, pch = 16, layout = c(5, 3, 2))
ix <- c(aperm(array(1:30, c(5, 2, 3)), c(1, 3, 2)))
p[ix]
请务必注意xyplot
公式中的扁平化变化。
页面
另一种方法是一次输出一个页面:
page <- factor((as.numeric(d$f1) - 1) %/% 5 + 1)
for(pg in levels(page)) {
p <- xyplot(y ~ x|f1+f2, data = d[pg == page, ], cex = .5, pch = 16)
plot(p, layout = c(5, 3))
}
答案 1 :(得分:3)
可以通过编写一个新的packet.panel
功能来实现面板的放置,该功能可以自动在所需位置绘制面板。
packet.panel.bycolumn <- function (layout, condlevels, page, row, column, skip) {
dims <- sapply(condlevels, length)
if(layout[2] != dims[2]) {
stop("rows in layout must be equal to rows of second conditioning variable")
}
panels.per.row <- layout[1]
panels.per.column <- layout[2]
total.columns <- dims[1]
panels.needed <- total.columns * panels.per.column
panels.per.page <- layout[1] * layout[2]
pages.needed <- ceiling(panels.needed / panels.per.page)
empty.columns <- (panels.per.row - total.columns) %% panels.per.row
panel.matrix <- rbind(matrix(1:panels.needed,ncol=panels.per.column),
matrix(NA, nrow=empty.columns, ncol=panels.per.column))
panel.order <- as.vector(aperm(array(panel.matrix,
dim=c(panels.per.row, pages.needed, panels.per.column)),
c(1,3,2)))
packet.order <- do.call(expand.grid, condlevels)[panel.order,]
panel.number <- 1 + (page - 1) * panels.per.page + (row - 1) * panels.per.row + (column - 1)
out <- as.numeric(packet.order[panel.number, ])
if (any(is.na(out))) out <- NULL
out
}
useOuterStrips
会更改布局,但之后可以更改。可以像这样实现所需的结果:
p <- xyplot(y~x|f1+f2, data=d, cex=0.5, pch=16)
p <- useOuterStrips(p)
p <- update(p, layout=c(5,3))
plot(p, packet.panel=packet.panel.bycolumn)