facet_grid中有多行

Luk*_*rau 4 r ggplot2 facet-wrap facet-grid

我有一个大致如下所示的数据集:

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)
Run Code Online (Sandbox Code Playgroud)

产生像这样的构面图:

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

构面图

是否有可能出现类似ncol=2in的行为,facet_wrap以便Location3和Location4出现在Location1和Location2下面?实际上,我大约有12个位置,这使得无法在一页上进行打印并且仍然清晰可辨。

C8H*_*4O2 5

您可以使用grid.arrange,例如:

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果确定x轴范围从上到下排列,则可以在第一个图上取消显示x轴刻度线/标签。