我想知道是否有一种简单的方法,可以使用基础图形系统在R绘图中添加具有对比背景的文本标签。到目前为止,我一直使用
rect()
函数与graphics::strheight()
和graphics::strwidth()
分别创建背景框,然后使用text()
放置我的文本。# Prepare a noisy background:
plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
## Parameters for my 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)
这是结果:
这个方法可以完成任务,但是当你开始使用pos
、adj
、offset
等调整文本位置时,就会遇到麻烦。我知道TeachingDemos::shadowtext()
可以让文本从背景中显现出来,但这只添加了一个轮廓而不是一个框。
我在寻找一种简单的方法来创建带有背景框的文本,类似于text(x, y, labels, bg = "grey20")
。我不能是第一个需要这样的功能的人,我可能只是漏掉了一些明显的东西。感谢您的帮助。谢谢!
box.col = NA
来关闭框边界。 - MichaelChiricolegend
函数有效,但对于text()
函数和其他使用它的函数(例如thigmophobe.labels()
)无效。 - Tomas