facet_grid中有多行

时间:2017-08-10 10:53:22

标签: 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)

这会产生这样的方面图:

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

Facet plot

是否可以在ncol=2中获取facet_wrap之类的行为,以便Location3和Location4显示在Location1和Location2下方?实际上我有大约12个位置,这使得无法在一个页面上打印并且仍然保持清晰。

1 个答案:

答案 0 :(得分:4)

您可以使用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)

enter image description here

如果您确定x轴范围从上到下排成一行,则可以在第一个图上抑制x轴刻度标记/标签。