facet_grid中有多行 [英] Multiple rows in facet_grid

查看:216
本文介绍了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_wrap中获得类似ncol=2的行为,以便Location3和Location4出现在Location1和Location2下面?实际上,我大约有12个位置,这使得无法在一页上进行打印并且仍然清晰可辨.

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.

推荐答案

您可以使用grid.arrange,如下所示:

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)

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

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.

这篇关于facet_grid中有多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆