在一个图中组合一个 ggplot2 对象和一个 lattice 对象
Combine a ggplot2 object with a lattice object in one plot
我想将 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 中的 lattice 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)
我想将 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 中的 lattice 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)