Math in R plots
R provides a way (see ?mathplot) to insert math into titles and labels in plots. An example: plot(1, main=expression(S[A])). This will create an S with a subscript A () in the title of the plot.
But what if you have a variable called x, and you want and the value of x in the title? For example, if the value of x is 3, you want to appear.
I’m sure there’s a simpler solution, but here’s the simplest one I’ve got:
- First, note that it would suffice to type in plot(1, main = expression(paste(S[A], ” = “, 3))). Of course, we want the value of x there, no matter what it is — not just 3. If we try plot(1, main = expression(paste(S[A], ” = “, x))), that will result in appearing in the title, not what we want.
- The solution is to create the string we would have typed if we knew the value of x. We do this like this: s <- paste(“plot(1, main = expression(paste(S[A], \” = \”, “, x, “)))”). If we now print the string s, it will show “plot(1, main = expression(paste(S[A], \” = \”, 3 )))” (if the value of x is 3).
- Now, we “run the string”: eval(parse(text = s)).
There are some more complicated but flexible solutions, like integrating postscript output from latex into R graphs (using psfrag).