Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot two graphs in same plot in R

I would like to plot y1 and y2 in the same plot.

x  <- seq(-2, 2, 0.05) y1 <- pnorm(x) y2 <- pnorm(x, 1, 1) plot(x, y1, type = "l", col = "red") plot(x, y2, type = "l", col = "green") 

But when I do it like this, they are not plotted in the same plot together.

In Matlab one can do hold on, but does anyone know how to do this in R?

like image 211
Sandra Schlichting Avatar asked Apr 01 '10 23:04

Sandra Schlichting


2 Answers

lines() or points() will add to the existing graph, but will not create a new window. So you'd need to do

plot(x,y1,type="l",col="red") lines(x,y2,col="green") 
like image 139
bnaul Avatar answered Oct 04 '22 12:10

bnaul


You can also use par and plot on the same graph but different axis. Something as follows:

plot( x, y1, type="l", col="red" ) par(new=TRUE) plot( x, y2, type="l", col="green" ) 

If you read in detail about par in R, you will be able to generate really interesting graphs. Another book to look at is Paul Murrel's R Graphics.

like image 29
4 revs, 4 users 70% Avatar answered Oct 04 '22 11:10

4 revs, 4 users 70%