我有一个大致如下所示的数据集:
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
中获得类似facet_wrap
的行为,以便Location3和Location4出现在Location1和Location2下方?实际上,我大约有12个位置,这使得无法在一页上进行打印并且仍然清晰可辨。 最佳答案
您可以使用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)
如果您确定x轴范围从上到下排列,则可以在第一个图上隐藏x轴刻度线/标签。