ggplot2: multiple plots with different variables in a single row, single grouping legend

前端 未结 1 2044
时光说笑
时光说笑 2020-12-13 22:34

While there are some topics going in the same general direction, I haven\'t found any that would deal with my issue specifically. Hence a new topic, and thanks in advance fo

相关标签:
1条回答
  • 2020-12-13 23:07

    Here is solution using package gridExtra and grid.arrange(). First, make three plots - one with legend (p1.leg) and two without legends.

    p1.leg <- ggplot(dsamp,aes(price,carat,colour=clarity))+geom_point()
    p1<-ggplot(dsamp,aes(price,carat,colour=clarity))+geom_point()+
          theme(legend.position="none")
    p2 <-ggplot(dsamp,aes(price,depth,colour=clarity))+geom_point()+
         theme(legend.position="none")
    

    Now you can get just legend from the first plot with function g_legend() that I borrowed from @Luciano Selzer answer to this question.

    g_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)}
    
    leg<-g_legend(p1.leg)
    

    Now you can combine both plots and legend with functions arrangeGrob() and grid.arrange(). In arrangeGrob() you can set widths for columns to get desired proportion between plots and legend.

    library(gridExtra)
    grid.arrange(arrangeGrob(arrangeGrob(p1,p2),leg,ncol=2,widths=c(5/6,1/6)))
    

    enter image description here

    UPDATE

    To put all plots in the same row:

    grid.arrange(arrangeGrob(p1,p2,leg,ncol=3,widths=c(3/7,3/7,1/7)))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题