从以下链接中获取提示使用 ggplot2 对齐两个图 http://rwiki.sciviews.org/doku.php?id=tips:graphics-ggplot2:aligntwoplots,我能够根据共同的 x 轴绘制 2 个“y”变量。我现在想做的是能够仅向其中一个面添加 geom_point 图层。该层使用与 d1 结构相同的不同数据集(d3)。当我添加图层时,它会在两个方面使用。是否可以仅将点分层到上面。
library(ggplot2)
x <- seq(1992, 2002, by = 2)
d1 <- data.frame(x = x, y = rnorm(length(x)))
xy <- expand.grid(x = x, y = x)
d2 <- data.frame(x = xy$x, y = xy$y, z = jitter(xy$x + xy$y))
d3 <- data.frame(x = x, y = 3+rnorm(length(x)))
d1$panel <- "a"
d2$panel <- "b"
d1$z <- d1$x
d <- rbind(d1, d2)
p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel ~ ., scale = "free")
p <- p + layer(data = d1, geom = c( "line"), stat = "identity")
###*p <- p + layer(data = d3, geom = c( "point"))* - This is the layer I intend to add only to the top panel
p <- p + layer(data = d2, geom = "line", stat = "identity")
p
只需添加panel
列至d3
使用要添加点集的面板。在你的情况下:
d3$panel = "a"
p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel ~ ., scale = "free")
p <- p + layer(data = d1, geom = c( "line"), stat = "identity")
p <- p + layer(data = d3, geom = c( "point"))
p <- p + layer(data = d2, geom = "line", stat = "identity")
p
这会产生正确的输出:
如果调用中提到的列facet_grid
不存在,ggplot2 假设它需要打印在所有方面。当您指定panel
,ggplot2 会考虑到它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)