Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a geom layer for a single panel in a faceted plot

Tags:

r

ggplot2

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
like image 207
Vijay Ivaturi Avatar asked May 20 '12 12:05

Vijay Ivaturi


People also ask

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

What does Facet_wrap do in Ggplot?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.

What is a GEOM layer?

Geometric objects, or geoms for short, perform the actual rendering of the layer, controlling the type of plot that you create. For example, using a point geom will create a scatterplot, while using a line geom will create a line plot.


1 Answers

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

which yields the correct output:

enter image description here

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.

like image 102
Paul Hiemstra Avatar answered Dec 08 '22 08:12

Paul Hiemstra