Mathematical annotations on R plots

September 2, 2015
By

(This article was first published on Hyndsight » R, and kindly contributed to R-bloggers)

I’ve always struggled with using plotmath via the expression function in R for adding mathematical notation to axes or legends. For some reason, the most obvious way to write something never seems to work for me and I end up using trial and error in a loop with far too many iterations.

So I am very happy to see the new latex2exp package available which translates LaTeX expressions into a form suitable for R graphs. This is going to save me time and frustration!

Here is a quick example showing a Lee-Carter decomposition of some mortality data.

library(demography)
library(latex2exp)
 
fit <- lca(fr.mort)
 
par(mfrow=c(2,2), mar=c(4,5,2,1), family="serif")
plot(fit$age, fit$ax, type="l", ylab=latex2exp("a_x"), xlab="Age: x")
plot(fit$age, fit$bx, type="l", ylab=latex2exp("b_x"), xlab="Age: x")
plot(0, type="n", axes=FALSE, xlab="", ylab="")
text(1, 0, latex2exp("m_{x,t} = a_x + k_tb_x + e_{x,t}"))
plot(fit$kt, ylab=latex2exp("k_t"), xlab="Year: t")

Rplot

There are several more examples in the package documentation.

The results are still a little ugly, but that is because of the limitations of base graphics in R. To get something more LaTeX-like, the tikzDevice package can be used as follows.

library(demography)
library(tikzDevice)
 
fit <- lca(fr.mort)
 
tikz("tikz-test.tex",width=15/2.54,height=12/2.54)
par(mfrow=c(2,2),mar=c(4,5,2,1),family="serif")
plot(fit[["age"]],fit$ax,type="l", 
     ylab="$a_x$", xlab="Age: $x$")
plot(fit[["age"]],fit$bx,type="l",
     ylab="$b_x$", xlab="Age: $x$")
plot(0,type="n",axes=FALSE,xlab="",ylab="")
text(1,0,"$m_{x,t} = a_x + k_tb_x + e_{x,t}$")
plot(fit$kt,ylab="$k_t$", xlab="Year: $t$")
dev.off()

Screenshot from 2015-09-02 17:12:50

While the results look much nicer, it is rather slow.

To leave a comment for the author, please follow the link and comment on their blog: Hyndsight » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)