10

I have a dataset that looks roughly like this:

names = tibble(NAME_2=c("Location1","Location2","Location3","Location4")) dates = tibble(date = seq(as.Date("2015-01-01"), as.Date("2016-12-31"), by="days")) types = tibble(type = c("comment","post")) df <- merge(names,dates) df <- merge(df, types) zero <- seq(from=0, to=200, by=1) df$n <- sample(zero, size=nrow(df), replace=TRUE) 

Which produces a facet plot like this:

ggplot(data = df, aes(x = date, y = n)) + geom_line() + facet_grid(type ~ NAME_2, scale = "free_y") 

Facet plot

Is it possible to get behavior like ncol=2 in facet_wrap so that Location3 and Location4 appear below Location1 and Location2? In reality I have about 12 locations, which makes it impossible to print on one page and still keep it legible.

3
  • Might be worth looking into the grid package. Commented Aug 10, 2017 at 11:05
  • 1
    Use facet_wrap!!! Commented Jul 31, 2019 at 15:54
  • 1
    facet_wrap works in one dimension, in that each facet produced is on one variable. If you want to do a x by y matrix, facet_grid is the way to go. Commented Feb 4, 2020 at 17:40

1 Answer 1

10

You could use grid.arrange, as in:

library(gridExtra) grid.arrange( ggplot(data = df[df$NAME_2 %in% c('Location1','Location2'),], aes(x = date, y = n)) + geom_line() + xlab(NULL) + facet_grid(type ~ NAME_2, scale = "free_y"), ggplot(data = df[df$NAME_2 %in% c('Location3','Location4'),], aes(x = date, y = n)) + geom_line() + facet_grid(type ~ NAME_2, scale = "free_y"), nrow=2) 

enter image description here

If you're sure that the x axis ranges line up from top to bottom, you could suppress the x axis tick marks/labels on the first plot.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, this works perfectly! Any idea on how to fix the y scale of one row facet? Say Location4 ranges not from 0 to 200, but 0 to 800: how can I keep the comment y-range but set the post y-range to 0 to 800 for both plots?
@Lukas I think you will have to use facet_wrap instead of facet_grid. you can also set ylim() but that will apply to each facet I believe.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.