堆叠具有相同轴尺寸的ggplot图

时间:2018-07-30 15:34:22

标签: r ggplot2

我有以下假设示例:

library(ggplot2)
library(gridExtra)

# df1
descr <- c("aaa","bbb","ccc")
v1 <- c(10,20,30)
df1 <- data.frame(descr,v1)

# df2
descr <- c("aaa","bbb","ccc")
v11 <- c(11111,22222,33333)
df2 <- data.frame(descr,v11)

# plot 1
p01 <- ggplot() +
  geom_point(data = df1, aes(x=descr, y=v1,color=v1), size=5))

# plot 2
p02 <- ggplot() +
  geom_point(data = df2, aes(x=descr, y=v11, color=v11), size=5)

# put them together and save
p_both <- arrangeGrob(p01,p02,nrow=2)
ggsave(file="testSave.png",p_both, width = 10, height = 15, units = "cm")

如您所见,轴不对齐。我知道在此特定示例中,我可以将dfs转换为长格式并使用构面,但这不是重点。 是否可以手动操纵轴以使其匹配,以使内部图完全相同?

谢谢!

1 个答案:

答案 0 :(得分:0)

如何尝试patchwork package

library(tidyverse)
# install.packages("devtools")
devtools::install_github("thomasp85/patchwork")
library(patchwork)

p01 + p02 + plot_layout(ncol = 1)

enter image description here