R绘图:是否可以在文本标签周围绘制边框,阴影或缓冲区? [英] R plots: Is there any way to draw 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 hide a lot of data plotted.
有什么方法可以在R图形中的文本标签周围放置边框,阴影或缓冲区?
Is there any way to put 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"功能,通过多次打印不同颜色的偏移量来在文本周围绘制光晕或边框. 格雷格·斯诺在这里.
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屋!