Adding to Plots

Statistical Computing, 36-350

Monday September 19, 2016

Adding points

To add points to an existing plot, use points()

n = 50
set.seed(0)
x = sort(runif(n, min=-2, max=2)) 
y = x^3 + rnorm(n)
plot(x, y)
points(x, x^3, pch=20, col="red")

Adding lines

To add lines to an existing plot, use lines()

plot(x, y)
lines(x, x^3, col="red")

points() and lines() can be called multiple times

These functions can be called repeatedly, to continue adding to the current plotting window

plot(x, y)
lines(x, x^3, col=2)
lines(x, x^3 + qnorm(0.90), col=3)
lines(x, x^3 + qnorm(0.10), col=4)

Adding straight lines

To add a line of the form \(y = a+bx\) to an existing plot, use abline(). Can also add vertical or horizontal lines. Lastly, can set line type, width, and color, as usual

plot(x, y)
abline(a=0, b=3)
abline(h=0, lty=2, lwd=3, col="red")

Adding text

To add text to an existing plot, use text()

plot(x, y)
lines(x, x^3, lwd=3)
text(0, -2.5, labels="This is a relatively flat region")

Adding a legend

To add a legend to an existing plot, use legend(). To set the legend position, the first two arguments can be x, y coordinates, or the first argument can be one of “topleft”, “topright”, “bottomleft”, “bottomright”

plot(x, y)
lines(x, x^3, col=2)
lines(x, x^3 + qnorm(0.90), col=3)
lines(x, x^3 + qnorm(0.10), col=4)
legend("topleft", legend=c("Mean", "Upper 90%", "Lower 10%"),
       lty=1, col=2:4)

Adding a rectangle

To add a rectangle to an existing plot, use rect(). Note: if the rectangle is colored, this will cover up whatever came before. This, and all additions to plots, follow layering rules

plot(x, y)
rect(-2, qnorm(0.10), 2, qnorm(0.90), # xleft, ybottom, xright, ytop
     col="lightgrey", border=NA)
lines(x, x^3, lwd=3)

Adding a polygon

To add a polygon to an existing plot, use polygon(). Note: if the polygon is colored, this will again cover up whatever came before

plot(x, y)
polygon(c(-2, 0, 2, 2, 0, -2), c(-3, -1, -3, 3, 1, 3), # x, y (vertex coords)
        col="lightgrey", border=NA) 
lines(x, x^3, lwd=3)

How to get layers working in your favor?

Suppose you want to draw points on top of a rectangle (or polygon). Two solutions: first, use plot() with type="n", then rect(), then points(); second, use custom transparent colors with rgb()

# First solution
plot(x, y, type="n")
rect(-2, qnorm(0.10), 2, qnorm(0.90), col="lightgrey", border=NA)
points(x, y)
lines(x, x^3, lwd=3)

# Second solution
plot(x, y)
rect(-2, qnorm(0.10), 2, qnorm(0.90), border=NA,
     col=rgb(0.5, 0.5, 0.5, 0.3)) # red, green, blue, alpha
lines(x, x^3, lwd=3)