Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a geom_line to all facets in a facet_wrap plot in R

I'm trying to create a facet_wrap plot that compares four separate lines to a common fifth line; the goal is to have this fifth line appearing on all four of the other facet_wrap plots.

Here's my minimal code:

library(ggplot2)

x    = c( 1,  3,  1,  3,  2,  4,  2,  4)
y    = c( 1,  3,  2,  4,  1,  3,  2,  4)
type = c("A","A","B","B","C","C","D","D")
data = data.frame(x,y,type)

x    = c( 4,  1)
y    = c( 1,  4)
type = c("E","E")
line = data.frame(x,y,type)

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
geom_line(data = line, aes(x,y))

I was hoping that adding the fifth line as an independent data.frame would allow me to do this, but it just adds it as a fifth facet, as in the following image:

Bad facet plot

I want the "E" facet to show up on all of the other plots. Any thoughts? I know that geom_vline, geom_hline, and geom_abline will all appear on all of the facets, but I'm not sure what makes them unique.

like image 360
hfisch Avatar asked Dec 04 '13 23:12

hfisch


People also ask

What code chunk do you add to the third line to create wrap around facets of the variable?

What code chunk do you add to the third line to create wrap around facets of the variable Company? You write the code chunk facet_wrap(~Company). In this code chunk: facet_wrap() is the function that lets you create wrap around facets of a variable.

What does facet wrap do in R?

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.

Which Ggplot function do you use to split up the plot into multiple plots?

Faceting. ggplot has a special technique called faceting that allows to split one plot into multiple plots based on a factor included in the dataset. We will use it to make one plot for a time series for each species.


1 Answers

You have specified type='E' in your line data.frame. If you want to have this line on type A,B,C,D, then create a data.frame with the types on which you want the line to display

xl    = c( 4,  1)
yl    = c( 1,  4)
type =rep(LETTERS[1:4], each=2)
line2 = data.frame(x=xl,y=yl,type)

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
   geom_line(data = line2)

You could also use annotate, which means you don't specify a data.frame, but pass the x and y values directly

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
  annotate(geom='line', x=xl,y=yl)

Both create

enter image description here

like image 139
mnel Avatar answered Oct 26 '22 11:10

mnel