tags:

views:

387

answers:

3

Hi, I was wondering if it was possible to graph three lines in R using fuctions. For instance, how could I get the functions:

3x+1 
4x+2
x+1

to show up on the same graph in r? Thanks so much!

+3  A: 

First decide the bounds, say 0 to 100, and make an empty plot including those points:

plot(c(0,100), c(0,100))

possibly of course with optional parameters such as axes=, xlab=, ylab=, and so on, to control various details of the axes and titling/labeling; then, add each line with abline(a, b) where b is the slope and a is the intercept, so, in your examples:

abline(1, 3)
abline(2, 4)
abline(1, 1)

Of course there are many more details you can control such as color (col= optional parameter), line type (lty=) and width (lwd=), etc, but this is the gist of it.

Alex Martelli
plot(c(0, 100), c(0, 100), type='n') is nicer. The 'n' prevents any output and just displays an empty plot (otherwise you get two points plotted at origin and (100,100)). The following abline commands will then display the lines.
ars
Excellent point (;-), @ars!
Alex Martelli
A: 

Here's another way using matplot:

> x <- 0:10
> matplot(cbind(x, x, x), cbind(3*x+1, 4*x+2, x+1), 
          type='l', xlab='x', ylab='y')

matplot(X, Y, ...) takes two matrix arguments. Each column of X is plotted against each column of Y.

In our case, X is a 11 x 3 matrix with each column a sequence of 0 to 10 (our x-values for each line). Y is a 11 x 3 matrix with each column computed off the x vector (per your line equations).

xlab and ylab just label the x and y axes. The type='l' specifies that lines are to be drawn (see other options by typing ?matplot or ?plot at the R prompt).

One nice thing about matplot is that the defaults can be nice for plotting multiple lines -- it chooses different colors and styles per line. These can also be modified: see ?matplot (and lty for more detail).

ars
A: 

You can also use the curve function. For example:

curve(3*x+1, from=-5, to=5)
curve(4*x+2, add=T)
curve(x+1, add=T)

Here the add parameter causes the plots to be put on the same graph

Matthew