1.2 Adding objects to an active plot

After the plot(x, y,...) function executes, the plot window remains active so that other objects can be added. The plot window deactivates when any code is run that doesn’t affect the plot. The following plot adds points, lines, text, an equation, and a legend to the sine plot.

x <- seq(0, 2 * pi, length.out = 50)
y <- sin(x)

eqn = expression(sin(x)%~~%sum(frac(f^~(k)*(0),'k!')~(x-0)^k, k==0, infinity))

plot(x = x, y = y, type = 'h', col = rainbow(50), lwd = 4)
lines(x = x, y = y, lty = 1, lwd = 3, col = 1)
points(x = x, y = y, pch = 16, col = rainbow(50), cex = 2)
abline(h = -0.5, v = 1.5)
text(x = 3, 
     y = .75,
     labels = eqn,
     cex = 1.5,
     family = 'serif',
     font = 2,
     adj = 0)
text(x = 3, 
     y = .35,
     labels = 'This is an equation',
     cex = 1.5,
     family = 'sans',
     font = 3,
     adj = 0)
legend('bottomleft',
       legend = 'sin(x)', 
       bty = 'n',
       fill = 'black')

1.2.0.1 Customizing the axes

For a plot of \(\sin(x)\), we would prefer to have the x-axis defined with respect to \(\pi\). The values displayed on the axes (and where the values are shown) can be customized using the axis() function. The plot below shows the values along the x-axis displayed as text.

plot(x = x,
     y = y,
     pch = 16,
     cex = c(seq(0.5,12.5,0.5),seq(12.5,0.5,-0.5)),
     col = rainbow(50),
     xaxt = 'n',
     las = 1,
     cex.axis = 1.25)
box(lwd = 1.5)
axis(side = 1, 
     labels = c('0', 'pi/2', 'pi', '3*pi/2', '2*pi'),
     at = c(0, pi/2, pi, 3*pi/2, 2*pi), 
     cex.axis = 1.25)

This looks ok, but we can do better by using parse for the labels

plot(x = x,
     y = y,
     pch = 16,
     cex = c(seq(0.5,12.5,0.5),seq(12.5,0.5,-0.5)),
     col = rainbow(50),
     xaxt = 'n',
     las = 1,
     cex.axis = 1.25)
box(lwd = 1.5)
axis(side = 1, 
     labels = parse(text = c('0', 'pi/2', 'pi', '3*pi/2', '2*pi')),
     at = c(0, pi/2, pi, 3*pi/2, 2*pi), 
     cex.axis = 1.25)

Or maybe we want both axes. In the plot below a second y-axis has been added to the top of the plot, the location of the axes has been moved in closer, and the ticks have be moved inside the plot box

plot(x = x,
     y = y,
     pch = 16,
     cex = c(seq(0.5,12.5,0.5),seq(12.5,0.5,-0.5)),
     col = rainbow(50),
     axes =  FALSE,
     las = 1,
     cex.axis = 1.25)
box(lwd = 1.5)
axis(side = 1, 
     labels = parse(text = c('0', 'pi/2', 'pi', '3*pi/2', '2*pi')),
     at = c(0, pi/2, pi, 3*pi/2, 2*pi), 
     cex.axis = 1.25,
     tck = 0.02,
     padj = 0.05)
axis(side = 2, cex.axis = 1.25, tck = 0.02, hadj = 0.75, las = 1)
axis(side = 3, cex.axis = 1.25, tck = 0.02, padj = 0.75)