Search code examples
rplotline

Adding 4 lines in one plot


Is it possible to add 4 lines in one plot in r? I am using the following code but the maximum lines I am able to add is only 3, the fourth line does not appear.

set.seed(5984)
r <- rnorm(1000, 0.5, 1)
i <- rnorm(1000, 0.45, 1)
r1 <- rnorm(1000, 4, 1)
r2 <- rnorm(1000, 4, 1)

plot(density(r), xlim=c(-5, 5), ylim=c(0, 0.45), col="#CD0000", lwd=2)
lines(density(i), col="#7D26CD", lwd=2)
lines(density(r1), lty=2, col="#FA8072", lwd=2)
lines(density(r2), col="#FF8247", lty=2, lwd=2)

Can someone help me with this?


Solution

  • It is possible to add multiple lines to one plot with lines().

    For exapmle:

    r <- rnorm(1000, 0.5, 1)
    i <- rnorm(1000, 0.45, 1)
    r1 <- rnorm(1000, 4, 1)
    r2 <- rnorm(1000, 4, 1)
    
    data <- data.frame(r,i,r1,r2)
    
    plot(0.0, xlim=c(-5, 5), ylim=c(0, 0.45))
    
    cl <- rainbow(ncol(data))
    
    for (i in 1:ncol(data)){
      lines(density(data[,i]),col = cl[i],lwd=2)
    }
    legend("topleft", legend = 1:ncol(data), col=cl, lwd=2) # optional legend
    

    enter image description here