在 R 中,以相同的 x 偏移量开始多图

问题描述

我在其他问题中寻找答案,找不到这个问题(或答案)。 使用 ggplot2 分别生成两个图。 然后使用 cowplot 包中的 plot_grid 函数将它们组合起来。 它们两个数据具有完全相同的公共日期数。 因此 x 轴是相同的,我希望两个图形的灰色框从同一个垂直点开始, 以便它们在时间上对齐。目前,由于ylab的大小不同,它们不是从同一条垂直线开始的。下面是图片说明:

enter image description here

解决方法

这可以通过 patchwork 包实现:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars,aes(hp,mpg)) +
  geom_point()

p2 <- ggplot(mtcars,mpg * 1000)) +
  geom_point()

p1 / p2

,

如果您想要一个仅使用 plot_grid 的解决方案,您可以执行以下操作(无可否认比 patchwork 包更黑客):

myPlot1 <- ggplot()
myPlot2 <- ggplot()

#get a ggplot that is the axis only
myYAxis1 <- get_y_axis(myPlot1) 
myYAxis2 <- get_y_axis(myPlot2)

#remove all y axis stuff from the plots themselves
myPlot1 <- myPlot1 + theme(axis.text.y = element_blank(),axis.title.y = element_blank(),axis.ticks.y = element_blank()) 
myPlot2 <- myPlot2 + theme(axis.text.y = element_blank(),axis.ticks.y = element_blank())

#reassemble plots
ratioAxisToPlot = .1 #determine what fraction of the arranged plot you want to be axis and what fraction you want to be plot)
plot1Reassembled <- plot_grid(myYAxis1,myPlot1,rel_widths = c(ratioAxisToPlot,1),ncol=2)
plot2Reassembled <- plot_grid(myYAxis2,myPlot2,ncol=2)

#put it all together
finalPlot <- plot_grid(plot1Reassembled,plot2Reassembled,nrow=2)