在使用网格排列在一页中布置两个图形时需要帮助

Need help in layout two graphs in one page using grid arrange

我有两个图,我想将它们显示在具有共同图例的一页上,我已经尝试了所有可能性,但其中 none 有效。 下面是代码和期望的结果:

library(ggplot2)
library("rnaturalearthdata")
library("rnaturalearth")

world <- ne_countries(scale = "medium", returnclass = "sf")
# first plot
grd1<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25),a= runif(325))
p1<- ggplot(data = world) +
  geom_sf(fill="antiquewhite") +
  coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
  geom_raster(data=grd1, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) +
  theme(legend.position="bottom")

# second plot
grd2<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25),a= runif(325))
p2<- ggplot(data = world) +
  geom_sf(fill="antiquewhite") +
  coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
  geom_raster(data=grd2, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) 


# Get the legend
library(gridExtra)
get_legend<-function(myggplot){
  tmp <- ggplot_gtable(ggplot_build(myggplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}
legend<- get_legend(p1)
p1<-p1+ theme(legend.position="none")
p2<-p2+ theme(legend.position="none")

# layout the two plots in one page
grid.arrange(
  grobs=list(p1, p2, legend), ncol=2,nrow=2,
  layout_matrix=rbind(c(1,2),c(3,3)),
  widths=c(4,4)
)

此代码产生以下结果

期望的结果应该是这样的

实现此目的的一种方法是利用 patchwork,通过 plot_layout 可以收集指南。为了完成这项工作,我们必须为填充比例设置相同的限制,以便填充图例相同(否则填充图例的比例会略有不同):

library(ggplot2)
library(patchwork)
library(rnaturalearthdata)
library(rnaturalearth)

world <- ne_countries(scale = "medium", returnclass = "sf")
# first plot
grd1<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25), a= runif(325))
p1<- ggplot(data = world) +
  geom_sf(fill="antiquewhite") +
  coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
  geom_raster(data=grd1, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) +
  scale_fill_continuous(limits = c(0, 1))
# second plot
grd2<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25), a= runif(325))
p2<- ggplot(data = world) +
  geom_sf(fill="antiquewhite") +
  coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
  geom_raster(data=grd2, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) +
  scale_fill_continuous(limits = c(0, 1)) 

p1 + p2 + 
  plot_layout(guides = "collect") & 
  theme(legend.position = "bottom")