In The Armchair

Math in R plots

Posted in Computers by Armchair Guy on April 5, 2011

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 (S_A) in the title of the plot.

But what if you have a variable called x, and you want S_A and the value of x in the title?  For example, if the value of x is 3, you want S_A = 3 to appear.

I’m sure there’s a simpler solution, but here’s the simplest one I’ve got:

  1. 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 S_A = x appearing in the title, not what we want.
  2. 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).
  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).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: