Plot two graphs in same plot in R

前端 未结 16 843
感情败类
感情败类 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:14

    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.

    0 讨论(0)
  • 2020-11-22 04:19

    we can also use lattice library

    library(lattice)
    x <- seq(-2,2,0.05)
    y1 <- pnorm(x)
    y2 <- pnorm(x,1,1)
    xyplot(y1 + y2 ~ x, ylab = "y1 and y2", type = "l", auto.key = list(points = FALSE,lines = TRUE))
    

    For specific colors

    xyplot(y1 + y2 ~ x,ylab = "y1 and y2", type = "l", auto.key = list(points = F,lines = T), par.settings = list(superpose.line = list(col = c("red","green"))))
    

    0 讨论(0)
  • 2020-11-22 04:20

    if you want to split the plot into two columns (2 plots next to each other), you can do it like this:

    par(mfrow=c(1,2))
    
    plot(x)
    
    plot(y) 
    

    Reference Link

    0 讨论(0)
  • 2020-11-22 04:20

    You can also create your plot using ggvis:

    library(ggvis)
    
    x  <- seq(-2, 2, 0.05)
    y1 <- pnorm(x)
    y2 <- pnorm(x,1,1)
    df <- data.frame(x, y1, y2)
    
    df %>%
      ggvis(~x, ~y1, stroke := 'red') %>%
      layer_paths() %>%
      layer_paths(data = df, x = ~x, y = ~y2, stroke := 'blue')
    

    This will create the following plot:

    0 讨论(0)
提交回复
热议问题