R-在同一图像中合并几个(15)ggplot对象

问题描述 投票:0回答:1

我只想在一张图像中合并15个ggplot对象。所有图在x和y上具有相同的尺寸。例如,有2个对象:

 library(ggplot2)     

 a <- c(1:10)
 b <- c(5,4,3,2,1,6,7,8,9,10)

 a2 <- c(1:10)
 b2 <- c(10:1)

 df1 <- as.data.frame(x=a,y=b)
 df2 <- as.data.frame(x=a2,y=b2)

 p1 <- ggplot(df1,aes(a, b)) + geom_line()
 p2 <- ggplot(df2,aes(a2, b2)) + geom_point()

我尝试使用plot_grid,但结果是ggplot对象的一张图像:

 library(cowplot)
 plot_grid(p1, p2, labels = "AUTO")

我也有网格,但与上面的结果相同。

我的临时解决方案是这样:

 merge <- p1 +geom_point(data=df2,aes(x=a2, y=b2))

但是我有15个ggplot对象。有什么办法做类似的事情吗?

 merge <- p1 + p2 +p3 ...+p15
 merge

请查看图片,并感谢您的帮助。

I want this resultUndesirable result

r ggplot2 plot merge ggplotly
1个回答
0
投票

我们可以使用

library(ggplot2)
ggplot() + 
      geom_line(data = df1, aes(a, b)) + 
      geom_point(data = df2, aes(a2, b2))

-输出

enter image description here


或者如果我们已经创建了对象,则将其reduce并绘制

library(purrr)
p0 <- ggplot()
p1 <- geom_line(data = df1, aes(a, b))
p2 <-    geom_point(data = df2, aes(a2, b2))
mget(paste0('p', 0:2)) %>%
          reduce(`+`)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.