Overlay base R graphics on top of ggplot2

后端 未结 2 1540
半阙折子戏
半阙折子戏 2021-01-06 14:45

I have a plot in ggplot and I wish to overlay a map legend that I have created with base R code. I do not know how to overlay base R graphics on top of a ggplot and would b

相关标签:
2条回答
  • 2021-01-06 15:37

    It might turn out to be easier to define your own custom legend,

    library(gridExtra)
    library(grid)
    
    stripGrob <- function(cols = c("yellow","orange","red","darkred"), 
                          labels= c(5,10,20), 
                          gp=gpar(fontsize=10,fontface="italic"), vp=NULL){
      n <- length(cols)
      rg <- rasterGrob(t(cols), y=1, vjust=1, interpolate = FALSE)
      sg <- segmentsGrob(x0=seq(1/n, 1-1/n, length.out=n-1),
                         x1=seq(1/n, 1-1/n, length.out=n-1),
                         y0=unit(1,"npc") - grobHeight(rg),
                         y1=unit(1,"npc") - grobHeight(rg) - unit(2,"mm"),
                         gp=gpar(lwd=2))
      tg <- textGrob(labels, x=seq(1/n, 1-1/n, length.out=n-1),
                     unit(1,"npc") - grobHeight(rg) - grobHeight(sg) - unit(1,"mm"), 
                     vjust=1)
    
      stripGrob <- gTree(children = gList(rg, tg, sg), gp=gp, vp=vp)
    }
    
    qplot(1,1) +
      annotation_custom(grob=stripGrob(), xmax=1.0)
    

    0 讨论(0)
  • 2021-01-06 15:44

    @baptiste's comment got me interested in trying to create a plot that would become the legend. Here's my attempt. I use geom_tile to create a plot that will become the legend. The OP didn't provide sample data so I've created a plot using the built-in mtcars data, just to have something to put the legend next to. Then I use grid.arrange to create the final plot-plus-legend layout.

    library(ggplot2)
    library(grid)
    library(gridExtra) 
    
    ## Create legend
    
    # Fake data
    dat = data.frame(x=1:4, y="Group", col=factor(1:4))
    
    # Create a plot that will become the legend
    legend = ggplot(dat, aes(x,y, fill=col)) + 
      geom_tile(show.legend=FALSE) +
      scale_x_continuous(breaks=c(1.5,2.5,3.5), labels=c(5,10,20)) +
      scale_fill_manual(values=c("yellow","orange","red","darkred")) +
      labs(y="", x="") +
      ggtitle("No. of Restaurants") +
      theme_bw() +
      theme(panel.border=element_blank(),
            axis.ticks.y=element_blank(),
            axis.text.y=element_blank())
    
    ## Create a plot to put next to the legend
    p1 = ggplot(mtcars, aes(mpg, wt)) + 
      geom_point() +
      theme(plot.margin=unit(c(0,0,0,0)))
    
    # Arrange plot and legend
    grid.arrange(p1, arrangeGrob(rectGrob(gp=gpar(col=NA)), 
                                 legend,
                                 rectGrob(gp=gpar(col=NA)),
                                 heights=c(0.42,0.16,0.42)), 
                 widths=c(0.8,0.2))
    

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