R 绘图:有没有办法在文本标签周围绘制边框、阴影或缓冲区? [英] R plots: Is there a way to draw a border, shadow or buffer around text labels?
问题描述
我想在单色图形的一条线上绘制一个标签.所以我需要在标签的每个字母上都有小的白色边框.
I want to plot a label over a line in a monochrome graphic. So I need small white border on each letter of the label.
文本标签矩形的边框或背景没有用,因为它隐藏了很多绘制的数据.
The border or background of rectangle of the text label is not useful because it hides a lot of the plotted data.
有没有办法在 R 图中的文本标签周围放置边框、阴影或缓冲区?
Is there a way to put a border, shadow or buffer around text labels in R plots?
shadowtext <- function(x, y=NULL, labels, col='white', bg='black',
theta= seq(pi/4, 2*pi, length.out=8), r=0.1, ... ) {
xy <- xy.coords(x,y)
xo <- r*strwidth('x')
yo <- r*strheight('x')
for (i in theta) {
text( xy$x + cos(i)*xo, xy$y + sin(i)*yo, labels, col=bg, ... )
}
text(xy$x, xy$y, labels, col=col, ... )
}
pdf(file="test.pdf", width=2, height=2); par(mar=c(0,0,0,0)+.1)
plot(c(0,1), c(0,1), type="l", lwd=20, axes=FALSE, xlab="", ylab="")
text(1/6, 1/6, "Test 1")
text(2/6, 2/6, "Test 2", col="white")
shadowtext(3/6, 3/6, "Test 3")
shadowtext(4/6, 4/6, "Test 4", col="black", bg="white")
shadowtext(5/6, 5/6, "Test 5", col="black", bg="white", theta = seq(pi/4, 2*pi, length.out=24))
dev.off()
上面的代码使用 koekenbakker 的解决方案.这对于 PNG 图形来说很好,但我需要一种不同的高分辨率 PDF 方法.
The code above use the solution from koekenbakker. This is fine for PNG graphic, but I need a different approach for high resolution PDF.
推荐答案
您可以试试这个shadowtext"功能,它通过以不同颜色的轻微偏移打印几次,在文本周围绘制光晕或边框.所有功劳均归于Greg Snow 此处.
You can try this 'shadowtext' function that draws a halo or border around the text by printing it several times with a slight offset in a different colour. All credits to Greg Snow here.
shadowtext <- function(x, y=NULL, labels, col='white', bg='black',
theta= seq(0, 2*pi, length.out=50), r=0.1, ... ) {
xy <- xy.coords(x,y)
xo <- r*strwidth('A')
yo <- r*strheight('A')
# draw background text with small shift in x and y in background colour
for (i in theta) {
text( xy$x + cos(i)*xo, xy$y + sin(i)*yo, labels, col=bg, ... )
}
# draw actual text in exact xy position in foreground colour
text(xy$x, xy$y, labels, col=col, ... )
}
# And here is an example of use:
# pdf(file="test2.pdf", width=2, height=2); par(mar=c(0,0,0,0)+.1)
plot(c(0,1), c(0,1), type="n", lwd=20, axes=FALSE, xlab="", ylab="")
rect(xleft = 0.5, xright = 1, ybottom = 0, ytop = 1, col=1)
text(1/6, 1/6, "Test 1")
shadowtext(2/6, 2/6, "Test 2", col='red', bg="blue")
shadowtext(3/6, 3/6, "Test 3", cex=2)
# `r` controls the width of the border
shadowtext(5/6, 5/6, "Test 4", col="black", bg="white", cex=4, r=0.2)
# dev.off()
这篇关于R 绘图:有没有办法在文本标签周围绘制边框、阴影或缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!