Boxed geom_text with ggplot2

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

    Instead of adding a bounding box, I would suggest changing the text color to white which can be done by doing

    Plot <- Plot + 
      geom_text(data = TextFrame, aes(x = X, y = Y, label = LAB), colour = 'white')
    

    The other approach would be to add an alpha to geom_point to make it more transparent

    Plot <- Plot + geom_point(size = 20, alpha = 0.5)
    

    EDIT. Here is a way to generalize Chase's solution to automatically compute the bounding box. The trick is to add the width and height of text directly to the text data frame. Here is an example

    Labels <- c("Alabama", "Alaska", "Arizona", "Arkansas", 
        "Pennsylvania + California")
    TextFrame <- data.frame(X = 4:8, Y = 4:8, LAB = Labels)
    TextFrame <- transform(TextFrame,
        w = strwidth(LAB, 'inches') + 0.25,
        h = strheight(LAB, 'inches') + 0.25
    )
    
    ggplot(data = SampleFrame,aes(x = X, y = Y)) + 
      geom_point(size = 20) +
      geom_rect(data = TextFrame, aes(xmin = X - w/2, xmax = X + w/2, 
        ymin = Y - h/2, ymax = Y + h/2), fill = "grey80") +
      geom_text(data = TextFrame,aes(x = X, y = Y, label = LAB), size = 4)
    

    enter image description here

提交回复
热议问题