Oneira
Oneira

Reputation: 1445

ggplot facet_grid with different y mapping

Is it possible to use facet_grid with lines (or columns) of the grid mapping different data?

I have the dataframe:

data=data.frame(x = c(6, 10, 4, 6, 4, 4, 9, 2, 4, 4, 5, 4, 2, 7, 8, 3), z1 = c(6, 6, 9, 8, 8, 2, 3, 1, 9, 8, 3, 9, 8, 1, 10, 7), z2 = c(8, 5, 6, 3, 9, 9, 8, 5, 1, 3, 5, 8, 8, 2, 3, 3), r = c('1L', '1L', '1L', '1L','1L', '1L', '1L', '1L', '2L', '2L', '2L', '2L', '2L', '2L', '2L', '2L'))
.

and currently I can combine 2 facet wraps for each y mapping I want:

p1 <- ggplot(data,aes(x=x,y=z1))+facet_wrap(~r)+geom_point(aes(colour=r))
p2 <- ggplot(data,aes(x=x,y=z2))+facet_wrap(~r)+geom_point(aes(colour=r))
arrangeGrob(p1,p2,nrow=2)

Resulting plot

Is is possible to combine those in a single facet_grid call?

Upvotes: 1

Views: 443

Answers (1)

MrFlick
MrFlick

Reputation: 206586

If you want all your data in one plot, it's better to just reshape your data. Here i've used the reshape2 library to make it easier

library(reshape2)
mm <- melt(data, id.vars=c("x","r"))
ggplot(mm,aes(x=x,y=value))+facet_grid(variable~r)+geom_point(aes(colour=r))

Upvotes: 1

Related Questions