2012-05-20 48 views
13

從以下鏈接Aligning two plots with ggplot2中獲取一個提示,我可以繪製與一個共同的x軸對齊的2個「y」變量。我現在想要做的就是隻能將一個geom_point圖層添加到其中一個方面。該圖層使用與d1具有相同結構的不同數據集(d3)。當我添加圖層時,它在兩個方面都得到了使用。是否有可能只分層點上面。在一個多面圖中爲單個面板添加一個geom圖層

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 
+1

+1,以及一個可重複的示例的句子問題 –

回答

8

就在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 

其產生正確的輸出:

enter image description here

如果調用提到facet_grid列不存在,GGPLOT2假定它需要在所有方面要被打印。當你指定panel時,ggplot2會考慮到它。

+0

+1謝謝,保羅。那很簡單 !在一個相關的問題中,就像在格子中一樣,有一種方法可以獲得面板編號的索引,以便能夠自定義各個面板(類似於格子中的panel.subscripts())。 –

+0

我不確定你的意思。我建議你在提供更多細節和一些示例代碼的地方創建一個新問題。 –

+1

ggplot2沒有面板號碼,因爲它會違反它的理念;相反,您可以通過其相應的分面變量來引用給定的面板。 – baptiste