如何在 ggplot 中重叠图形轴并在两个轴上扩展一个轴标题?

How do I overlap figure axes and extend one axes title across two axes in ggplot?

我有一个包含四个图的图形。所有 y-axis 都是温度,两个 x-axis 是时间 1 和时间 2。我正在使用 R 中的 patchwork 包和 plot_layout() 函数将所有四个图堆叠并对齐成一个 2x2 图。因为所有 y-axes 都是相同的变量,我只想显示一个 y-axis 标题在图的左侧,但我不知道该怎么做。我也想 cover-up 右栏两个图上的 y-axes,但是当我移动数字时,右栏与左栏重叠(我想要相反)。

这是我到目前为止所做的一个例子。

library(ggplot2)
library(patchwork)

df1 <- data.frame(x1 = rnorm(20), y1 = rnorm(20))
df2 <- data.frame(x2 = rnorm(20), y2 = rnorm(20))
df3 <- data.frame(x3 = rnorm(20), y3 = rnorm(20))
df4 <- data.frame(x4 = rnorm(20), y4 = rnorm(20))

p1 <- ggplot(data = df1, aes(x = x1, y = y1)) +
  geom_point() +
  ylab("Temperature") +
  theme_bw() +
  theme(panel.grid = element_blank(),
           plot.margin = unit(c(0,0,0,0),"cm"))

p2 <- ggplot(data = df2, aes(x = x2, y = y2)) +
  geom_point() +
  ylab("Temperature") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        plot.margin = unit(c(0,0,0,0),"cm"))

p3 <- ggplot(data = df3, aes(x = x3, y = y3)) +
  geom_point() +
  xlab("Time1") +
  ylab("Temperature") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        plot.margin = unit(c(-0.5,0,0,0),"cm"))

p4 <- ggplot(data = df4, aes(x = x4, y = y4)) +
  geom_point() +
  xlab("Time2") +
  ylab("Temperature") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        plot.margin = unit(c(-0.5,0,0,0),"cm"))

p5 <- p1/p2/p3/p4 + plot_layout(ncol = 2, heights = c(1,1))
p5

产生这个数字:

不过,我最终希望这个数字看起来像这样:

使用 facet_grid 怎么样?不过,我们需要先进行一些数据清理:

library(dplyr)
library(tidyr)
libary(ggplot2)
df1 <- data.frame(Sample = 1, Time1 = rnorm(20), y = rnorm(20))
df2 <- data.frame(Sample = 1, Time2 = rnorm(20), y = rnorm(20))
df3 <- data.frame(Sample = 2, Time1 = rnorm(20), y = rnorm(20))
df4 <- data.frame(Sample = 2, Time2 = rnorm(20), y = rnorm(20)) 

data <- bind_rows(mget(ls(pattern = "df[0-9]"))) %>%
  pivot_longer(cols = c(-y,-Sample), 
               names_to = "Time",
               values_to = "x") %>%
  dplyr::filter(complete.cases(.))
data
## A tibble: 80 x 4
#   Sample       y Time       x
#    <dbl>   <dbl> <chr>  <dbl>
# 1      1 -0.449  Time1  0.768
# 2      1 -1.10   Time1  0.410
# 3      1 -0.529  Time1 -1.98 
# 4      1 -0.485  Time1 -1.09 
# 5      1  0.128  Time1  1.06 
## … with 75 more rows

现在我们有了正确格式的数据,我们可以 facet_wrap 按时间:


ggplot(data = data, aes(x = x, y = y)) +
  geom_point() +
  ylab("Temperature") +
  xlab(element_blank()) + 
  facet_grid(cols = vars(Time), rows = vars(Sample), scales = "free",switch = "both") + 
  theme_bw() +
  theme(panel.grid = element_blank(),
           plot.margin = unit(c(0,0,0,0),"cm"),
        strip.background = element_blank(),
        strip.placement = "outside", strip.text.y = element_blank())

请注意,无法在同一行中使用自由 y 轴,也无法在同一列中使用自由 x 轴。