Global legend using grid.arrange (gridExtra) and lattice based plots

前端 未结 3 1351
忘了有多久
忘了有多久 2020-12-17 05:41

I am producing four plots using xyplot (lattice) and further combine them with grid.arrange (gridExtra).

I would like to obtain a graph with a common global legend.

3条回答
  •  情书的邮戳
    2020-12-17 06:11

    One possible solution is to use ggplot, hinted here.

    Here is the resulting figure:

    my.cols <- 1:3
    
    my.grid.layout <- rbind(c(1,2),
                            c(3,3))
    
    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)
      }
    
    legend.plot <- ggplot(iris, aes(x=Petal.Length, y=Sepal.Width,colour=Species)) +
                                      geom_line(size=1) + # legend should show lines, not points or rects ...
                                      theme(legend.position="right", legend.background = element_rect(colour = "black"),
                                            legend.key = element_rect(fill = "white")) + # position, box and background colour of legend
                                      scale_color_manual(values=my.cols, name = "Categories") + # manually insert colours as used in corresponding xyplot
                                      guides(colour = guide_legend(reverse=T)) # inverts order of colours in legend
    
    mylegend <- g_legend(legend.plot)
    plot1 <- xyplot(Sepal.Width ~ Petal.Length, groups = Species, data = iris, type = 'l',
                    par.settings = simpleTheme(col=my.cols))
    plot2 <- xyplot(Sepal.Length ~ Petal.Length, groups = Species, data = iris, type = 'l',
                    par.settings = simpleTheme(col=my.cols))
    
    
    grid.arrange(plot1,plot2,mylegend,layout_matrix=my.grid.layout,             
             top=textGrob(gp=gpar(col='black',fontsize=20),"Some useless example"))
    

提交回复
热议问题