Including mathematical expressions on your plots
Mathematical expressions on graphs are made possible through a combination of two commands, expression()
and paste()
, and also through the
substitute()
command.
By itself, the expression()
command allows you to include mathematical symbols. For example, consider the following syntax:
plot(c(1,2,3), c(2,4,9), xlab = expression(phi))
This will create a small plot with the Greek symbol phi as the horizontal axis label.
The combination of expression()
and paste()
allows you to include mathematical symbols on your graph, along with letters, text, or numerals. Its syntax is expression(paste())
. Where necessary (that is, where you need mathematical expressions as axis labels), you can switch off the default axes and include Greek symbols by writing them out in English. You can create fractions through the frac()
command. Note the plus or minus sign, which is achieved though the syntax %+-%
.
The following is an example based on a similar example in the excellent book Statistics: An Introduction using R, Michael J. Crawley, Wiley-Blackwell. I recommend this book to everyone who uses R—both students and professional researchers alike.
We first create a set of values from –7
to +7
for the horizontal axis. We have 71 such values.
x <- seq(-7, 7, len = 71)
Now we create interesting x and y axes labels. We will disable the x axis in order to create our own axis.
plot(x, cos(x),type="l",xaxt="n", xlab=expression(paste("Angle",theta)), ylab=expression("sin "*beta)) axis(1, at = c(-pi, -pi/2, 0, pi/2, pi), lab = expression(-alpha, -alpha/2, 0, alpha/2, alpha))
We insert mathematical text at appropriate places on the graph:
text(-pi,0.5,substitute(sigma^2=="37.8")) text(-pi/16, -0.5, expression(paste(frac(gamma*omega, sigma*phi*sqrt(3*pi)), " ", e^{frac(-(3*x-2*mu)^2, 5*sigma^2)}))) text(pi,0,expression(hat(y) %+-% frac(se, alpha)))
The resulting graph is as follows:
By comparing your own code with that used to produce this graph, you should be able to work out how to create your own mathematical expressions.