【发布时间】:2015-09-01 13:11:34
【问题描述】:
感谢"Combine a ggplot2 object with a lattice object in one plot" 中的出色回答以及一些进一步的想法,我可以在ggplot 旁边绘制lattice 图:
library(ggplot2)
library(lattice)
library(gtools)
library(plyr)
library(grid)
library(gridExtra)
set.seed(1)
mdat <- data.frame(x = rnorm(100), y = rnorm(100), veryLongName = rnorm(100),
cluster = factor(sample(5, 100, TRUE)))
cols <- c("x", "y", "veryLongName")
allS <- adply(combinations(3, 2, cols), 1, function(r)
data.frame(cluster = mdat$cluster,
var.x = r[1],
x = mdat[[r[1]]],
var.y = r[2],
y = mdat[[r[2]]]))
sc <- ggplot(allS, aes(x = x, y = y, color = cluster)) + geom_point() +
facet_grid(var.x ~ var.y) + theme(legend.position = "top")
sc3d <- cloud(veryLongName ~ x + y, data = mdat, groups = cluster)
scG <- ggplotGrob(sc)
sc3dG <- gridExtra:::latticeGrob(sc3d)
ids <- grep("axis-(l|b)-(1|2)|panel", scG$layout$name)
scG$grobs[ids[c(2, 5, 8)]] <- list(nullGrob(), nullGrob(), nullGrob())
grid.newpage()
grid.draw(scG)
pushViewport(viewport(0, 0, width = .515, height = .46,
just = c("left", "bottom")))
grid.rect()
grid.draw(sc3dG)
正如您在图片中看到的那样,格子图周围有相当多的边距,在其顶部,z 轴的轴标签被切割(不是这种情况,我单独绘制 lattice 图) .
那么我怎样才能摆脱这种行为,从而解决以下两个问题:
- 去掉
viewport和lattice绘图之间的内边距 - 避免
lattice图中的标签被剪切。
我尝试使用viewport 的clip 选项,但没有成功。那么,该怎么办呢?
2020 年更新
编辑代码和答案以反映 grob 中的新命名约定。
【问题讨论】: