Friday, January 4, 2008

special symbols on R plot

Sometimes we need put special symbols, like Greek letters and italic type, on the plots. Sometimes, we also want to put mathematical annotation on the plot. In R we can use the function expression() do this job:

Sample codes

xlab.name = expression(paste(italic(vti), Delta, sep=""))
ylab.name = expression(mu * "ml")
main.name = expression(paste(plain(sin) * phi))
plot(0, 0, xlab=xlab.name, ylab=ylab.name, main=main.name, xlim=c(-pi, pi), ylim=c(-1.5, 1.5), axes=FALSE)
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi), labels = expression(-pi, -pi/2, 0, pi/2, pi))
axis(2)
box()
text(-pi/2, 0, expression(hat(alpha) == (X^t * X)^{-1} * X^t * y))
text(pi/2, 0, expression(paste(frac(1, sigma*sqrt(2*pi)), plain(e)^{frac(-(x-mu)^2, 2*sigma^2)}, sep="")), cex = 1.2)

### #######################
PS: for the subscript expression,
We should use
> ylab.name = expression(sigma[21])

############################
There are webpages talking about this issue in details. Mathematical Annotation in R: http://rweb.stat.umn.edu/R/library/grDevices/html/plotmath.html
##############################
others:
main=expression(paste(italic(Sch9), Delta, " (18s and 5.8s)")),

However, if we want to use a variable in the expression, we should use substitute:
e.g.

n <- 20
plot(0, 0, main = substitute(paste(n[i], " = ", k), list(k = n)));
i=2;
range.name = substitute(paste(italic(Sch9), Delta, " ", p, "/", k, " hr"), list(k = i*12, p = (i+1)*12));
text(0, 0, range.name)
# with a variable, we can use for iteration to produce multiple tags
##############################

5 comments:

Alex Ruiz Euler said...

Thanks.

Tal Galili said...

Lovely blog.

If you ever got back to blogging,
You are welcome to join
R-bloggers.com

Cheers,
Tal

Laurilla said...

Do you know how to add accented words, e.g. "DuraciĆ³n" to plot labels and legends. Thanks !

lee woo said...

Words are but symbols for the relations of things to one another and to us; nowhere do they touch upon absolute truth. See the link below for more info.


#symbols
www.ufgop.org

Whales_Cats said...

HI, I have been trying to make the symbol delta in a italic font with no success at all, and if I try using the unicode for small delta it actually writes delta as a "d" not as the Greek symbol.....I tried with the other Greek symbols and it was very easy, but delta is the one I need...HELP please!