Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple rows in facet_grid

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.

like image 745
LukasKawerau Avatar asked Aug 10 '17 10:08

LukasKawerau


People also ask

Can you facet wrap by 2 variables?

Note that you can add as many (categorical) variables as you'd like in your facet wrap, however, this will result in a longer loading period for R.

What is the difference between Facet_grid and Facet_wrap?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

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. If you have only one variable with many levels, try facet_wrap() .

When should you use Facet_wrap?

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. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.


1 Answers

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.

like image 140
C8H10N4O2 Avatar answered Sep 28 '22 02:09

C8H10N4O2