Text labels with background colour in R -
i wondering if there simple way add text labels contrasting background r plot using base graphic system. until have used rect()
function graphics::strheight()
, graphics::strwidth()
separately create background box on place text using text()
:
# prepare noisy background: plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050") ## parameters text: mytext <- "some text" poscoordsvec <- c(0.5, 0.5) cex <- 2 ## background 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) ## place text: text(poscoordsvec[1], poscoordsvec[2], mytext, cex = cex)
this result:
this job quite tedious , run trouble when start using pos
, adj
, offset
etc. tweak positioning of text. aware of teachingdemos::shadowtext()
make text stand out background adds outline instead of box.
i looking simple way create text background box, text(x, y, labels, bg = "grey20")
. can't first person require such functionality , missing obvious. appreciated. thanks
base graphics
using legend
:
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)
output:
geom_label
:
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)
Comments
Post a Comment