Boxed geom_text with ggplot2

后端 未结 7 538
迷失自我
迷失自我 2021-01-03 23:40

I am developing a graphic with ggplot2 wherein I need to superimpose text over other graphical elements. Depending on the color of the elements underlying the text, it can b

7条回答
  •  日久生厌
    2021-01-04 00:39

    Update for ggplot2 v0.9

    library(ggplot2)
    library(proto)
    
    btextGrob <- function (label,x = unit(0.5, "npc"), y = unit(0.5, "npc"), 
        just = "centre", hjust = NULL, vjust = NULL, rot = 0, check.overlap = FALSE, 
        default.units = "npc", name = NULL, gp = gpar(), vp = NULL,  f=1.5) {
        if (!is.unit(x)) 
          x <- unit(x, default.units)
        if (!is.unit(y)) 
          y <- unit(y, default.units)
        grob(label = label, x = x, y = y, just = just, hjust = hjust, 
             vjust = vjust, rot = rot, check.overlap = check.overlap, 
             name = name, gp = gp, vp = vp, cl = "text")
        tg <- textGrob(label = label, x = x, y = y, just = just, hjust = hjust, 
                       vjust = vjust, rot = rot, check.overlap = check.overlap)
        w <- unit(rep(1, length(label)), "strwidth", as.list(label))
        h <- unit(rep(1, length(label)), "strheight", as.list(label))
        rg <- rectGrob(x=x, y=y, width=f*w, height=f*h,
                       gp=gpar(fill="white", alpha=0.3,  col=NA))
    
        gTree(children=gList(rg, tg), vp=vp, gp=gp, name=name)
      }
    
    GeomText2 <- proto(ggplot2:::GeomText, {
      objname <- "text2"
    
      draw <- function(., data, scales, coordinates, ..., parse = FALSE, na.rm = FALSE) {
        data <- remove_missing(data, na.rm, 
          c("x", "y", "label"), name = "geom_text2")
    
        lab <- data$label
        if (parse) {
          lab <- parse(text = lab)
        }
    
        with(coord_transform(coordinates, data, scales),
          btextGrob(lab, x, y, default.units="native", 
            hjust=hjust, vjust=vjust, rot=angle, 
            gp = gpar(col = alpha(colour, alpha), fontsize = size * .pt,
              fontfamily = family, fontface = fontface, lineheight = lineheight))
        )
      }
    
    })
    
    geom_text2 <- function (mapping = NULL, data = NULL, stat = "identity", position = "identity", 
    parse = FALSE,  ...) { 
      GeomText2$new(mapping = mapping, data = data, stat = stat,position = position, 
      parse = parse, ...)
    }
    
    
    qplot(wt, mpg, data = mtcars, label = rownames(mtcars), size = wt) +
       geom_text2(colour = "red")
    

提交回复
热议问题