在拼面图中为单个面板添加几何图层

Vij*_*uri 15 r ggplot2

以从以下链接的提示比对两个地块与GGPLOT2,我能够绘制刻面对付共同的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
Run Code Online (Sandbox Code Playgroud)

Pau*_*tra 10

只需将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
Run Code Online (Sandbox Code Playgroud)

产生正确的输出:

在此输入图像描述

如果调用中提到的列facet_grid不存在,ggplot2假定需要在所有方面打印.指定时panel,ggplot2会将其考虑在内.