ggplot 多方面和组合 x 轴

ggplot Multiple facets and combined x axis

我正在尝试创建一个图表来跟踪多个因素在几天内的结果。理想情况下,我希望我的 x 轴是 Day,天数位于该特定日期代表的中间,y 轴是结果,facet 是 Lot (1-4)。由于重复次数可能会有所不同,因此我很难使用可重复的文本将一天放在底部的中心。

我正在使用此 post 中显示的想法:Multi-row x-axis labels in ggplot line chart 但一直无法取得任何进展。

这是我一直在使用的一些代码和到目前为止的情节。 x 轴太忙了,我正在努力巩固它。

data <- data.frame(System = rep(c("A", "B"), each = 120), Lot = rep(1:4, each = 30),
               Day = rep(1:5, each = 6), Rep = rep(1:6, 40), Result = rnorm(240))

library(ggplot2)

ggplot(data, aes(x = interaction(Day, Rep, lex.order = TRUE), y = Result, color = System, group = System)) +
geom_point() +
geom_line() +
theme(legend.position = "bottom") + 
facet_wrap(~Lot, ncol = 1) +
geom_vline(xintercept = (which(data$Rep == 1 & data$Day != 1)), color = "gray60")

我不是 100% 确定这是否正是您所追求的,但这将使一天在 x 轴上居中。

library(dplyr)
library(tidyr)
library(ggplot2)

df <- data.frame(System = rep(c("A", "B"), each = 120), Lot = rep(1:4, each = 30),
                   Day = rep(1:5, each = 6), Rep = rep(1:6, 40), Result = rnorm(240))

df <- df %>% 
     unite(Day_Rep, Day, Rep, sep = ".", remove = F) %>% 
     mutate(Day_Rep = as.numeric(Day_Rep))


ggplot(df, aes(x = Day_Rep, y = Result, color = System, group = System)) +
     geom_point() +
     geom_line() +
     theme(legend.position = "bottom") + 
     facet_wrap(~Lot, ncol = 1) +
     scale_x_continuous(labels = df$Day, breaks = df$Day + 0.5)+
     geom_vline(xintercept = setdiff(unique(df$Day), 1))