Plot two graphs in same plot in R

前端 未结 16 828
感情败类
感情败类 2020-11-22 03:37

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\")         


        
16条回答
  •  情深已故
    2020-11-22 04:10

    Use the matplot function:

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

    use this if y1 and y2 are evaluated at the same x points. It scales the Y-axis to fit whichever is bigger (y1 or y2), unlike some of the other answers here that will clip y2 if it gets bigger than y1 (ggplot solutions mostly are okay with this).

    Alternatively, and if the two lines don't have the same x-coordinates, set the axis limits on the first plot and add:

    x1  <- seq(-2, 2, 0.05)
    x2  <- seq(-3, 3, 0.05)
    y1 <- pnorm(x1)
    y2 <- pnorm(x2,1,1)
    
    plot(x1,y1,ylim=range(c(y1,y2)),xlim=range(c(x1,x2)), type="l",col="red")
    lines(x2,y2,col="green")
    

    Am astonished this Q is 4 years old and nobody has mentioned matplot or x/ylim...

提交回复
热议问题