您可以从感兴趣的地块中提取图例,然后将该图例与地块并排放置。
#libraries:
library(ggplot2)
library(ggpubr)
library(gridExtra)
library(grid)
#example plots:
p1 <- ggplot(mtcars) +
geom_point(aes(x=mpg,y=qsec,color = factor(cyl)))
p2 <- ggplot(mtcars) +
geom_point(aes(x=mpg,y=4*drat,color = factor(cyl))) +
theme(legend.title = element_text(size = 15,face = "bold"),legend.position="bottom")
#function to extract the legend of a ggplot; source:
#https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
get_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs,function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
#arranging the legend and plots in a grid:
p2_legend <- get_legend(p2)
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),p2 + theme(legend.position="none"),nrow=2),p2_legend,nrow=2,heights=c(10,1))
本文链接:https://www.f2er.com/2983486.html