30
votes

A way to draw the curve corresponding to a given function is this:

fun1 <- function(x) sin(cos(x)*exp(-x/2))
plot (fun1, -8, 5)

How can I add another function's curve (e.g. fun2, which is also defined by its mathematical formula) in the same plot?

4

4 Answers

30
votes
plot (fun2, -8, 5, add=TRUE)

Check also help page for curve.

28
votes

Using matplot:

fun1<-function(x) sin(cos(x)*exp(-x/2))
fun2<-function(x) sin(cos(x)*exp(-x/4))
x<-seq(0,2*pi,0.01)
matplot(x,cbind(fun1(x),fun2(x)),type="l",col=c("blue","red"))
9
votes

Use the points function. It has the same exact syntax as plot.

So, for instance:

fun1 <- function(x) sin(cos(x)*exp(-x/2))

x <- seq(0, 2*pi, 0.01)
plot (x, fun1(x), type="l", col="blue", ylim=c(-0.8, 0.8))
points (x, -fun1(x), type="l", col="red")

Note that plot parameters like ylim, xlim, titles and such are only used from the first plot call.

7
votes

Using par()

fun1 <- function(x) sin(cos(x)*exp(-x/2))
fun2 <- function(x) sin(cos(x)*exp(-x/4))

plot(fun1, -8,5)
par(new=TRUE)
plot(fun2, -8,5)