tags:

views:

77

answers:

4

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?

+5  A: 

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.

nico
how about lines directly :)
VitoshKa
Yeah, that's another option. It really depends what you need to do... there are several ways of accomplish this task in R. :)
nico
+3  A: 

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)
Brandon Bertelsen
I use the same paradigm all the time. You probably want an ylim=range(...) expression in the first plot, maybe a different color in the second plot, play with xlab and ylab, suppress axes if the scaling doesn't overlap etc pp. At least for a more general solution. What you showed does answer the question asked :)
Dirk Eddelbuettel
+4  A: 

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"))
mbq
matplot is the best answer, since if you start adding curves you might end up with them going off the current plot area. matplot sorts this all out for you, and makes sure both functions stay in view.
Spacedman
@Spacedman: what if you don't know the functions in advance? :)
nico
+3  A: 
plot (fun2, -8, 5, add=TRUE)

Check also help page for curve.

Marek
Note that you cannot always use the `add` parameter: it works here because you are passing a function to plot, but if you write, for instance, `plot(x,y, add=TRUE)` you will just get a warning that `add` is not a graphical parameter.
nico
@nico Yes. This is very special case cause `plot` for function call `curve`. That's why always use `curve` to plot functions.
Marek