2019-10-03

How to add a text box to a plot in R

Problem

We want to add a text box to a plot in R. First, we will use a very convoluted code to get it done.

# A plot
plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")

# Text box parameters
myText <- "some Text"
posCoordsVec <- c(0.5, 0.5)
cex <- 2

# Rectangle
textHeight <- graphics::strheight(myText, cex = cex)
textWidth <- graphics::strwidth(myText, cex = cex)
pad <- textHeight*0.3
rect(xleft = posCoordsVec[1] - textWidth/2 - pad, 
        ybottom = posCoordsVec[2] - textHeight/2 - pad, 
        xright = posCoordsVec[1] + textWidth/2 + pad, 
        ytop = posCoordsVec[2] + textHeight/2 + pad,
        col = "lightblue", border = NA)

# Text coordinates
text(posCoordsVec[1], posCoordsVec[2], myText, cex = cex)

Solution

  • Base graphics
  • We use the function legend, same colour for the box line (box.col) and the background (bg), adjusting the text inside with the argument adj.

    plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
    legend(0.4, 0.5, "Some text", box.col = "lightblue", bg = "lightblue", adj = 0.2)
    
  • ggpplot2
  • With ggplot2 we need the function geom_label. The text will be automatically aligned inside the box, we remove the borders with label.size = NA.

    library(ggplot2)
    df <- data.frame(x = runif(1000), y = runif(1000))
    ggplot(data = df, aes(x = x , y = y))+ 
      geom_point(alpha = 0.2)+
      geom_label(aes(x = 0.5, y = 0.5, label = "Some text"), 
                 fill = "lightblue", label.size = NA, size = 5)
    

References

No hay comentarios:

Publicar un comentario

Nube de datos