我想将 ggplot2
与 lattice
绘图对象结合起来。由于这两个包都是基于grid
我想知道这是否可能?理想情况下,我会在 ggplot2 中完成所有操作,但无法绘制 3d 散点图。
假设我有以下数据:
set.seed(1)
mdat <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100),
cluster = factor(sample(5, 100, TRUE)))
首先,我想在 ggplot2 中创建一个散点图矩阵:
library(ggplot2)
library(gtools)
library(plyr)
cols <- c("x", "y", "z")
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)
到目前为止一切顺利。现在我想创建一个包含所有变量的 lattice
3d 散点图:
library(lattice)
sc3d <- cloud(z ~ x + y, data = mdat, groups = cluster)
现在我想将 sc
和 sc3d
合并在一个图中。我怎样才能做到这一点?也许借助grid
或gridExtra
(pushViewport
、arrangeGrob
?)?或者我可以在 ggplot 中生成 3d 散点图吗?理想情况下,我希望在 ggplot 的空面板中看到 3D 绘图,但我想这要求太多了,所以对于初学者来说,我很高兴了解如何安排这两个绘图并排。
最佳答案
library(gridExtra); library(lattice); library(ggplot2)
grid.arrange(xyplot(1~1), qplot(1,1))
您可以用 gtable 中的网格 block 替换空面板,但由于轴等原因,它看起来不太好。
g <- ggplotGrob(sc)
lg <- gridExtra:::latticeGrob(sc3d)
ids <- which(g$layout$name == "panel")
remove <- ids[2]
g$grobs[[remove]] <- lg
grid.newpage()
grid.draw(g)
关于r - 将 ggplot2 对象与晶格对象组合在一个图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32328765/