Search code examples
rggplot2facet-grid

ggplot: Generate facet grid plot with multiple series


I have following data frame:

  Quarter        x        y         p         q
1  2001   8.714392 8.714621 3.3648435 3.3140090
2  2002   8.671171 8.671064 0.9282508 0.9034387
3  2003   8.688478 8.697413 6.2295996 8.4379698
4  2004   8.685339 8.686349 3.7520135 3.5278024

My goal is to generate a facet plot where x and y column in one plot in the facet and p,q together in another plot instead of 4 facets.

If I do following:

x.df.melt <- melt(x.df[,c('Quarter','x','y','p','q')],id.vars=1)
ggplot(x.df.melt, aes(Quarter, value, col=variable, group=1)) + geom_line()+
  facet_grid(variable~., scale='free_y') +
  scale_color_discrete(breaks=c('x','y','p','q'))

I all the four series in 4 different facets but how do I combine x,y to be one while p,q to be in another together. Preferable no legends.

enter image description here


Solution

  • One idea would be to create a new grouping variable:

    x.df.melt$var <- ifelse(x.df.melt$variable == "x" | x.df.melt$variable == "y", "A", "B")
    

    You can use it for facetting while using variable for grouping:

    ggplot(x.df.melt, aes(Quarter, value, col=variable, group=variable)) + geom_line()+
      facet_grid(var~., scale='free_y') +
      scale_color_discrete(breaks=c('x','y','p','q'), guide = F)
    

    enter image description here