在一个图

时间:2015-09-01 10:00:53

标签: r ggplot2 lattice

我想将ggplot2lattice绘图对象组合在一起。由于这两个软件包都基于grid,我想知道这是否可行?理想情况下,我会在ggplot2中执行所有操作,但我无法绘制三维分散。

假设我有以下数据:

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三维散点图:

library(lattice)
sc3d <- cloud(z ~ x + y, data = mdat, groups = cluster)

现在我想将scsc3d合并到一个单独的地块中。我怎样才能做到这一点?也许在gridgridExtrapushViewportarrangeGrob?)的帮助下?或者我可以在ggplot中生成三维散点图吗?理想情况下,我希望在ggplot的空面板中看到3d图,但我想这个问题要求太多,所以对于初学者我很乐意学习如何安排这两个并排的情节。

ggplot lattice

1 个答案:

答案 0 :(得分:6)

library(gridExtra); library(lattice); library(ggplot2)
grid.arrange(xyplot(1~1), qplot(1,1))

enter image description here

您可以通过gtable中的格子grob替换空面板,但由于轴等原因,它看起来不是很好。

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)

enter image description here