如何解决在 R 中,以相同的 x 偏移量开始多图
我在其他问题中寻找答案,找不到这个问题(或答案)。 使用 ggplot2 分别生成两个图。 然后使用 cowplot 包中的 plot_grid 函数将它们组合起来。 它们两个数据具有完全相同的公共日期数。 因此 x 轴是相同的,我希望两个图形的灰色框从同一个垂直点开始, 以便它们在时间上对齐。目前,由于ylab的大小不同,它们不是从同一条垂直线开始的。下面是图片说明:
解决方法
这可以通过 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。