Mathematical Symbols on Plots

To write on plots using more intricate symbols such as mathematical symbols or Greek letters we use expression or substitute. Here are some examples of their use. First, we produce a plot of sin φ against the phase angle φ over the range −πr to +π radians:

x <- seq(-4, 4, len = 101)
plot(x,sin(x),type="l",xaxt="n",
        xlab=expression(paste("Phase Angle ",phi)),
        ylab=expression("sin "*phi))
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
        lab = expression(-pi, -pi/2, 0, pi/2, pi))

Note the use of xaxt = "n" to suppress the default labelling of the x axis, and the use of expression in the labels for the x and y axes to obtain mathematical symbols such as phi (φ) and pi (π). The more intricate values for the tick marks on the x axis are obtained by the axis function, specifying 1 (the x (‘bottom’) axis is axis no. 1), then using the at function to say where the labels and tick marks are to appear, and lab with expression to say what the labels are to be.

Suppose you wanted to add χ2 = 24.5 to this graph at location (−π/2, 0.5). You use text with substitute, like this:

text(-pi/2,0.5,substitute(chi^2=="24.5"))

Note the use of ‘double equals’ to print a single equals sign. You can write quite complicated formulae on plots using paste to join together the elements of an equation. Here is the density function of the normal written on the plot at location (π/2, −0.5):

text(pi/2, -0.5, expression(paste(frac(1, sigma*sqrt(2*pi)), " ",
       e^{frac(-(x-mu)^2, 2*sigma^2)}))) ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.