29

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?

Brani
  • 7,896
  • 14
  • 42
  • 48

4 Answers4

29
plot (fun2, -8, 5, add=TRUE)

Check also help page for curve.

Marek
  • 45,585
  • 13
  • 89
  • 116
  • 10
    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 Oct 29 '10 at 09:52
  • 3
    @nico Yes. This is very special case cause `plot` for function call `curve`. That's why always use `curve` to plot functions. – Marek Oct 29 '10 at 10:07
28

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
  • 18,025
  • 6
  • 45
  • 70
  • 6
    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 Oct 29 '10 at 09:04
  • 2
    @Spacedman: what if you don't know the functions in advance? :) – nico Oct 29 '10 at 09:53
9

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
  • 48,112
  • 17
  • 80
  • 111
  • Yeah, that's another option. It really depends what you need to do... there are several ways of accomplish this task in R. :) – nico Oct 29 '10 at 09:49
7

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
  • 40,095
  • 33
  • 147
  • 245
  • 1
    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 Oct 29 '10 at 15:39