R 中的多 X 轴

Multi- X-Axis in R

我正在尝试创建一个如下图所示的图,但在涉及多个 x 轴时我真的很吃力。任何帮助,将不胜感激。提供的图形的示例代码。

样图:

df <- data.frame(Time=c(" ","Phase 1","Phase 1","Phase 1","Phase 1"," ",
                            " ","Phase 2","Phase 2","Phase 2","Phase 2"," "),
                 Condition=c("BO", "BO", "BO", "BO","BO","BO", 
                        "OB","OB","OB","OB","OB","OB"), 
                 Phase=c("Baseline", "T1", "T2", "T1", "T2", "Follow-Up"),
                 Change=c(0,-2.84, -5.02, -6.81,-7.41,-6.80, 0, -3.35,-6.92,-7.05,-6.59,-6.41))

尝试按照可用代码 here。但是并没有走多远。

这里有一个建议:

library(tidyverse)
library(grid)
library(ggthemes)

# data preparation
df1 <- df %>% 
    mutate(Phase = as_factor(Phase)) %>% 
    group_by(id_Group = cumsum(Phase=="Baseline")) %>% 
    mutate(id = row_number()) %>% 
    mutate(Time = paste("Phase", id_Group, sep = " ")) %>% 
    ungroup() 

# plot

# vector for labels
label_x <- c("Baseline", "T1", "T2", "T1", "T2", "Follow-Up")

# textGrob
phase1 <- textGrob("Phase 1", gp=gpar(fontsize=13, fontface="bold"))
phase2 <- textGrob("Phase 2", gp=gpar(fontsize=13, fontface="bold"))

# plot
ggplot(df1, aes(x=factor(id), y=Change, colour=Condition, group=Condition)) +
    geom_line(size=1 ) +    
    scale_x_discrete(breaks = 1:6, labels= label_x) +
    theme_economist_white(gray_bg = FALSE) +
    theme(plot.margin = unit(c(1,1,2,1), "lines")) +
    annotation_custom(phase1,xmin=2,xmax=3,ymin=-8.2,ymax=-8.2) + 
    annotation_custom(phase2,xmin=4,xmax=5,ymin=-8.2,ymax=-8.2) +
    coord_cartesian(clip = "off")