Plot two graphs in the same plot in R

423    Asked by ClaudineTippins in Data Science , Asked on Jun 3, 2021

How can I plot two graphs in same plot in R, I am using this command to perform my task but it isn’t working.

 x <- seq(-3, 4, 1.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 2, 2)
plot(x, y1, type = "2", col = "blue")
plot(x, y2, type = "l", col = "yellow")

 How R  plot two graphs on top of each other? Please help me with it.


Answered by Chris Dyer

There are several methods to perform this task I am sharing a few with you:

Method-1:

Use par, it will plot on the same graph but axis will be different. E.x.

plot( x, y1, type="l", col="blue" )

par(new=TRUE)

plot( x, y2, type="l", col="yellow" )

Method-2:

You can add lines() or points() to the existing graph but it won’t create a new window.

plot(x,y1,type="l",col="blue")

lines(x,y2,col="yellow")

Method-3:

Use matplot function, e.x.

matplot(x, cbind(y1,y2),type="l",col=c("blue","yellow"),lty=c(1,1))

There are some other methods too, I hope one of this help you with your issue.



Your Answer

Interviews

Parent Categories