r - 将 ggplot2 对象与晶格对象组合在一个图中

标签 r ggplot2 lattice

我想将 ggplot2lattice 绘图对象结合起来。由于这两个包都是基于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)

现在我想将 scsc3d 合并在一个图中。我怎样才能做到这一点?也许借助gridgridExtra(pushViewportarrangeGrob?)?或者我可以在 ggplot 中生成 3d 散点图吗?理想情况下,我希望在 ggplot 的空面板中看到 3D 绘图,但我想这要求太多了,所以对于初学者来说,我很高兴了解如何安排这两个绘图并排。

ggplot lattice

最佳答案

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

enter image description here

您可以用 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)

enter image description here

关于r - 将 ggplot2 对象与晶格对象组合在一个图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32328765/

相关文章:

r - 在 R 中满足条件后过滤组中的后续行

r - 使用 R 进行线性预测 : How to access the predicted parameter(s)?

r - ggplot 的 scale_y_log10 行为

r - 热图中 x 轴上的对角线标签方向

r - 将轴刻度与点阵直方图中的箱对齐

r - Jupyter 的 IRkernel

regex - 如何防止regmatchs丢弃非匹配项?

r - 如何根据列条目向 ggplot2 中的 map 图添加额外的图例?

r - 如何更快地创建 1000 页的 pdf?

删除条形图中每个面板未使用的因素