使用 Cowplot 垂直对齐不同轴的绘图

Align plot with different axes vertically using Cowplot

我正在尝试对齐左侧 y-axis 的三个图(y-axis 上的比例不同)。换句话说,我希望红轴对齐:

但是,第一个图的 y-axis 与左下图的 y-axis 不对齐。

代码

# Libraries
library(tidyverse)
library(cowplot)

df1 <- data.frame(x = seq(0, 100, 1), 
                  y = seq(100, 0, -1))

df2 <- data.frame(x = seq(0, 10, 0.1), 
                  y = seq(1, 10^9, length.out = 101 ) )

p1 <- ggplot(data = df1) + 
  geom_line(aes(x = x, y = y))

p2 <- ggplot(data = df2) + 
  geom_line(aes(x = x, y = y))

combi_p2 <- plot_grid(p2, p2, nrow = 1)
plot_grid(p1, combi_p2, ncol = 1, axis = "l", align = "v")

尝试修复

利用here提供的信息,我重写了代码的最后一部分:

require(grid)                    # for unit.pmax()
p1 <- ggplotGrob(p1)             # convert to gtable
combi_p2 <- ggplotGrob(combi_p2) # convert to gtable

p1.widths <- p1$widths[1:3]      # extract the first three widths, 
                                 # corresponding to left margin, y lab, and y axis
combi_p2.widths <- combi_p2$widths[1:3]                 # same for combi_p2 plot
max.widths <- unit.pmax(p1.widths, combi_p2.widths)     # calculate maximum widths
p1$widths[1:3] <- max.widths                            # assign max. widths to p1 gtable
combi_p2$widths[1:3] <- max.widths                      # assign max widths to combi_p2 gtable

# plot_grid() can work directly with gtables, so this works
plot_grid(p1, combi_p2, labels = "AUTO", ncol = 1)

遗憾的是,我无法修复对齐方式:

问题

如何使用 R 中的 cowplot 将顶部绘图的 y-axis 与左侧底部绘图对齐?

我想你可以使用 ggplotGrob 并将它们与 gtable_rbindgtable_cbind 放在一起。最后,你可以用grid.draw()

画图
df1 <- data.frame(x = seq(0, 100, 1), 
              y = seq(100, 0, -1))
df2 <- data.frame(x = seq(0, 10, 0.1), 
              y = seq(1, 10^9, length.out = 101 ) )
p1 <- ggplot(data = df1) + 
              geom_line(aes(x = x, y = y))
p2 <- ggplot(data = df2) + 
              geom_line(aes(x = x, y = y))

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)

frame_g2 <- gtable_frame(g2 , debug = TRUE)

frame_combi <- gtable_frame(gtable_cbind(frame_g2,frame_g2),
                            width = unit(2, "null"),
                            height = unit(1, "null"))
frame_g1  <-
   gtable_frame(
     g1,
     width = unit(1, "null"),
     height = unit(1, "null"),
     debug = TRUE
    )

 grid.newpage()
 all_frames <- gtable_rbind(frame_g1, frame_combi)
 grid.draw(all_frames)

剧情是这样的。

Claus O. Wilke 提出了 cowplot 解决方案 here

它基于 align_plot 函数,它首先沿 y 轴将顶部绘图与左底部绘图对齐。然后将对齐的图传递给 plot_grid 函数。

# Libraries
library(tidyverse)
library(cowplot)

df1 <- data.frame(x = seq(0, 100, 1), 
                  y = seq(100, 0, -1))

df2 <- data.frame(x = seq(0, 10, 0.1), 
                  y = seq(1, 10^9, length.out = 101 ) )

p1 <- ggplot(data = df1) + 
  geom_line(aes(x = x, y = y))

p2 <- ggplot(data = df2) + 
  geom_line(aes(x = x, y = y))

plots <- align_plots(p1, p2, align = 'v', axis = 'l')
bottom_row <- plot_grid(plots[[2]], p2, nrow = 1)

plot_grid(plots[[1]], bottom_row, ncol = 1)