Problema
Queremos añadir un cuadro de texto a un gráfico en R. A continuación, podemos ver una primera solución, pero el código es demasiado verboso y alambicado.
# Un gráfico
plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
## Parámetros para el texto
myText <- "some Text"
posCoordsVec <- c(0.5, 0.5)
cex <- 2
# Rectángulo
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)
# Ubicación del texto
text(posCoordsVec[1], posCoordsVec[2], myText, cex = cex)
Solución
- Base graphics
Empleamos la función legend, con el mismo color en los bordes y relleno que en la solución inicial, y ajustamos el texto en el interior con el argumento 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
Con ggplot2 usamos la función geom_label. A diferencia de legend en base graphcis, el texto se centra automáticamente dentro del cuadro, con label.size = NA eliminamos los bordes
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)
Referencias