Match legend text color in geom_text to symbol

前端 未结 4 603
暗喜
暗喜 2020-12-01 18:34

I am trying to color match the text of the legend to the color of text produced by a factored variable using geom_text. Here is a minimal working example:

4条回答
  •  爱一瞬间的悲伤
    2020-12-01 19:27

    This answer is based on the answers given by Mike H. from the question here and by user20650 from this question.

    To get the colours:

      pGrob <- ggplotGrob(p1)
      g.b   <- pGrob[["grobs"]][[which(pGrob$layout$name=="guide-box")]]
      l     <- g.b[[1]][[1]][["grobs"]]
      # get grobs for legend symbols (extract colour)
      lg    <- l[sapply(l, function(i) grepl("GRID.text", i))]
      clr   <- mapply(FUN=function(x){x$gp$col},x=lg)
    

    Then use the following methods

       gb  <- which(grepl("guide-box", pGrob$layout$name))
       gb2 <- which(grepl("guides", pGrob$grobs[[gb]]$layout$name))
       label_text <- which(grepl("label",pGrob$grobs[[gb]]$grobs[[gb2]]$layout$name))
    
       pGrob$grobs[[gb]]$grobs[[gb2]]$grobs[label_text] <- 
       mapply(FUN = function(x, y) {x[["children"]][[1]][["children"]][[1]]$gp <- gpar(col =y); return(x)},
              x =   pGrob$grobs[[gb]]$grobs[[gb2]]$grobs[label_text],
              y =  clr, SIMPLIFY = FALSE)
    

    After it, you will get the same output file

    grid.draw(pGrob)
    

    I am providing this answer because in the second chunk of the code, the argument, which is assigned to x$gp in mapply function, should be a gpar object. That is a mistake in Mike H.'s answer and I am fixing it.

    Thank you.

提交回复
热议问题