如何重新排列 facet_wrap/_grid 的面板?

问题描述

这里是菜鸟。我一整天都被这张图难住了,像 this 和这个 this 这样的解决方案似乎能解决我的问题,但我无法让它们为我工作。

我有一个数据框,它是我尝试使用 ggplot 绘制的以下示例的大版本。

# create data
df <- data.frame(
  "ID" = rep(1:5,each = 4),"Date" = c(seq(as.Date("2019/09/18"),by = "day",length.out = 4),seq(as.Date("2019/09/18"),seq(as.Date("2020/08/07"),seq(as.Date("2020/09/12"),seq(as.Date("2020/09/29"),length.out = 4)),"MaxDepth" = round(runif(20,min = 10,max = 50),1),"Trip" = rep(1:5,each = 4)
)

# plot using ggplot
ggplot(df,aes(Date,MaxDepth,col = factor(Trip))) + 
  geom_line() + 
  facet_grid(ID ~ format(Date,"%Y"),scales = "free_x") + 
  scale_y_reverse() + 
  scale_x_date(date_labels = "%b") + 
  labs(title = "Daily maximum depth\n",x = "",y = "Depth [m]\n",col = "Fishing trip")

结果很好地显示一个两列、十一行的多面图,以钓鱼之旅为颜色。

但是,它包含许多空面板,我想通过创建一个仍然包含所有 11 个 ID 行但由两列具有的相同拆分标签分隔的单列图来避免这些空面板。 IE。我希望 LHS 2019 图中的两个人将 2019 年标签放在顶部,并由 2020 年标签与其他 9 个人分开。

Like in this mock up

希望这很清楚。请纠正我或让我知道如何改进以获得更好的问题。 感谢任何帮助!即使这些建议表明这不是一种很好的表示方式,或者类似的事情根本不可能。谢谢大家!

解决方法

这是一种可能的方法。我不确定它是否适用于您的真实数据。

library(ggplot2)
library(patchwork)
library(dplyr)

plot_fun <- function(dtt){
    ggplot(dtt,aes(Date,MaxDepth,col = factor(Trip))) + 
        geom_line() + 
        facet_grid(ID ~ format(Date,"%Y"),scales = "free_x") + 
        scale_y_reverse() + 
        scale_x_date(date_labels = "%b") + 
        labs(x = NULL,y = NULL,col = "Fishing trip")
}

p1 <- plot_fun(df %>% filter(format(Date,'%Y') == '2019'))
p2 <- plot_fun(df %>% filter(format(Date,'%Y') == '2020'))

p1 / p2
ggsave('~/Downloads/test.png',width = 6,height = 6)

enter image description here