Boxed geom_text with ggplot2

后端 未结 7 491
迷失自我
迷失自我 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:37

    Update for ggplot2 1.0.1

    GeomText2 <- proto(ggplot2:::GeomText, {
      objname <- "text2"
    
      draw <- function(., data, scales, coordinates, ..., parse = FALSE, na.rm = FALSE
                        ,hjust = 0.5, vjust = 0.5
                        ,expand = c(1.1,1.2), bgcol = "black", bgfill = "white", bgalpha = 1) {
        data <- remove_missing(data, na.rm, c("x", "y", "label"), name = "geom_text")
    
        lab <- data$label
        if (parse) {
          lab <- parse(text = lab)
        }
    
        with(coord_transform(coordinates, data, scales),{
            sizes <- llply(1:nrow(data),
                function(i) with(data[i, ], {
                    grobs <- textGrob(lab[i], default.units="native", rot=angle, gp=gpar(fontsize=size * .pt))
                    list(w = grobWidth(grobs), h = grobHeight(grobs))
                })
            )
            w <- do.call(unit.c, lapply(sizes, "[[", "w"))
            h <- do.call(unit.c, lapply(sizes, "[[", "h"))
            gList(rectGrob(x, y,
                         width = w * expand[1], 
                         height = h * expand[length(expand)],
                         just = c(hjust,vjust),
                         gp = gpar(col = alpha(bgcol, bgalpha), fill = alpha(bgfill, bgalpha))),
                .super$draw(., data, scales, coordinates, ..., parse))
        })
      }
    })
    
    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, ...)
    }
    

提交回复
热议问题