Adding text directly to a plot is a useful way of annotating features of your graphic. But if the background of the chart is quite busy, as is often the case with image plots or dense scatterplots, the text can sometimes be difficult to read. Placing the text in a "calm" area of the plot can help, but this isn't an option if the graph is dynamically generated from simulated or live data.
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('A')
yo <- r*strheight('A')
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, ... )
}
x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = terrain.colors(100), axes = FALSE)
contour(x, y, volcano, levels = seq(90, 200, by = 5),
add = TRUE, col = "peru")
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
text(531,544, 'Maunga Whau Volcano', col='lightsteelblue')
shadowtext(206,257, 'Caldera Rim', col='lightsteelblue')
The text "Maunga Whau Volcano" is plotted with the ordinary text function; lacking an outline it's a bit hard to read on the background. The text "Caldera Rim" is plotted with an outline by the shadowtext function.
Download the Rcode for the function and graphic here: shadowtext.R (0.8K)
Eek! We'll be doing drop shadow and WordArt curvy things next!
If your graphics device supports transparency, I'd put the text on a transparent box, using strwidth and strheight to get the location where the text is going. Here's a start:
boxText <- function(x,y,string){
width=strwidth(string)
width=width+strwidth("m")
height=strheight(string)
height=height*2
rect(x-width/2,y-height/2,x+width/2,y+height/2,col="#77777766",border=NA)
text(x,y,string)
return(res)
}
Then do:
boxText(206,257, 'Caldera Rim')
Adjust colours and transparency levels to taste...
Barry
Posted by: Barry Rowlingson | May 27, 2009 at 10:17