在多面图中为单个面板添加一个geom层 [英] Add a geom layer for a single panel in a faceted plot
问题描述
从以下链接中获取提示将两个图与ggplot2对齐,我能够针对共同的x轴绘制2个"y"变量.我现在想做的就是能够将geom_point图层仅添加到其中一个构面中.该层使用与d1具有相同结构的其他数据集(d3).当我添加该图层时,它将同时在两个方面使用.是否可以仅在上面对点进行分层.
Taking a cue from the following link Aligning two plots with ggplot2, I was able to plot 2 "y" variables faceted against a common x axis. What I want to do now is to be able to add a geom_point layer to only one of the facets. This layer uses a different dataset(d3) with a same structure as d1. When I add the layer it gets used on both facets. Is it possible to layer the points only the upper facet.
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
即可.就您而言:
Just add the panel
column to d3
with the panel you want to add the point set to. In your case:
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会将其考虑在内.
If the column mentioned in the call to facet_grid
is not present, ggplot2 assumes it needs to be printed on all facets. When you specify panel
, ggplot2 will take it into account.
这篇关于在多面图中为单个面板添加一个geom层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!