Suppose you want to plot several lines or curves or functions simultaneously. Here is an example plot and a few different ways to produce it, so that you can use whichever you feel most comfortable with.
lines
For the first method, we create a new plot with the plot
function, and then we can use the function lines
to add points connected by lines to the plot. The function abline
can draw lines determined by intercept and slope, or horizontal or vertical lines. Note in the example below, it is convenient that the sin
function acts nicely on vectors so we can write things like sin(xvec)
. If the function we want to plot does not act nicely on vectors, we may need to use sapply
or a loop to do the same thing.
xvec <- seq(-10, 10, by=.1)
yvec <- sin(xvec)
# yvec <- sapply(X = xvec, FUN = sin) # alternative to the above
plot(xvec, yvec, type="l", col="black", xlab="x", ylab="y")
yvec2 <- sin(xvec/1.5)
lines(xvec, yvec2, col="red")
yvec3 <- sin(xvec/2.0)
lines(xvec, yvec3, col="blue")
abline(h=c(-1,1), lty=2)
abline(h=0, lty=2, col="green")
curve
If the functions we are plotting act nicely on vectors, we can use the function curve
, which plots an expression written as a function of x. The argument add=TRUE
tells R to add the curve to an existing plot rather than start a new plot. If you have defined functions that don’t work on vectors, this won’t work.
plot(sin, -10, 10, col="black", xlab="x", ylab="y")
curve(sin(x/1.5), col="red", add=TRUE)
curve(sin(x/2.0), col="blue", add=TRUE)
abline(h=c(-1,1), lty=2)
abline(h=0, lty=2, col="green")
Under the same conditions as the last method, we could define and plot functions as follows.
f <- function(x){
return(sin(x/1.5))
}
g <- function(x){
return(sin(x/2.0))
}
plot(sin, -10, 10, col="black", xlab="x", ylab="y")
plot(f, -10, 10, col="red", add=TRUE)
plot(g, -10, 10, col="blue", add=TRUE)
abline(h=c(-1,1), lty=2)
abline(h=0, lty=2, col="green")