Thursday, April 2, 2015

Add text using relative plot region coordinates



Here is a simple but useful function for adding text to a plot device using the relative x, y coordinates (i.e. between 0 and 1). I found myself programming these few lines repeatedly and decided to finally bundle it into a function, called reltext(). The function can be found below, and is also available in the sinkr package (https://github.com/marchtaylor/sinkr).
Example 2:
Example 3:

Script to reproduce the examples:
reltext <- function(relx=0.5, rely=0.5, labels = seq_along(relx), ...){
  usr <- par("usr")
  x <- usr[1] + relx*(usr[2]-usr[1])
  y <- usr[3] + rely*(usr[4]-usr[3])
  text(x, y, labels, ...)
}
 
set.seed(1)
n <- 100
a <- 3
b <- 5
x <- rnorm(n)
y <- a + b*x + rnorm(n, sd=2)
fit <- lm(y ~ x)
 
png("reltext_ex1.png", width=3.5, height=3.5, units="in", res=300, family="Arial", type="cairo")
op <- par(mar=c(3,3,0.5,0.5), mgp=c(1.5,0.5,0), tcl=-0.25, las=1, bty="l")
plot(x, y)
abline(fit, lty=2, col=4)
reltext(0, 0.95, pos=4, col=4,
  labels=bquote( italic(y) == .(sprintf("%0.2f", (coef(fit)[1])))+.(sprintf("%0.2f", (coef(fit)[2])))~"*"~italic(x) )
)
reltext(0, 0.85, pos=4, col=4,
  labels=bquote( bolditalic(R)^2 == .(round(summary(fit)$adj.r.squared,2)) )
)
par(op)
dev.off()
 
png("reltext_ex2.png", width=3.5, height=3.5, units="in", res=300, family="Arial", type="cairo")
op <- par(mar=c(4,4,1,1))
plot(x, y)
abline(fit, lty=2, col=8)
reltext(c(0,0.95), c(0.95, 0.05), pos=c(4,2), col=c(3,4), labels=c("text1", "text2"))
par(op)
dev.off()
 
 
png("reltext_ex3.png", width=3.5, height=3.5, units="in", res=300, family="Arial", type="cairo")
op <- par(mar=c(4,4,1,1), ps=8)
plot(x, y, t="n")
reltext(0.1, labels="text", pos=1, col=1)
reltext(0.1, labels="text", pos=2, col=2)
reltext(0.1, labels="text", pos=3, col=3)
reltext(0.1, labels="text", pos=4, col=4)
 
reltext(0.9, labels="text", pos=1, col=1)
reltext(0.9, labels="text", pos=2, col=2)
reltext(0.9, labels="text", pos=3, col=3)
reltext(0.9, labels="text", pos=4, col=4)
 
reltext(0.1, 0.9, labels="text", pos=1, col=1)
reltext(0.1, 0.9, labels="text", pos=2, col=2)
reltext(0.1, 0.9, labels="text", pos=3, col=3)
reltext(0.1, 0.9, labels="text", pos=4, col=4)
 
reltext(0.9, 0.1, labels="text", pos=1, col=1)
reltext(0.9, 0.1, labels="text", pos=2, col=2)
reltext(0.9, 0.1, labels="text", pos=3, col=3)
reltext(0.9, 0.1, labels="text", pos=4, col=4)
 
par(op)
dev.off()
Created by Pretty R at inside-R.org


No comments:

Post a Comment