Overlay base R graphics on top of ggplot2

后端 未结 2 1564
半阙折子戏
半阙折子戏 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)
    

提交回复
热议问题