facet_grid 中的多行

2024-02-29

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

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")

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


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

如果您确定 x 轴范围从上到下排列,您可以抑制第一个图上的 x 轴刻度线/标签。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

facet_grid 中的多行 的相关文章

随机推荐