Apply lines() to columns of a data frame/matrix; each line with a different color

apply, dataframe, line, matrix, r

Solution

Try `matplot()`:

df <- cbind(sort(rnorm(10)), sort(rnorm(10,-2)), sort(rlnorm(10)))
matplot(df, type="b", lty=1, pch=1, col=c("blue", "red", "black"))

Problem

I am trying to come up with a solution that doesn't involve using other packages such as ggplot. While plotting multiple lines is pretty straightforward, I haven't figured out a way to apply different values of an argument - e.g., different colors - to different lines. The code below (with the resulting plot) was my attempt, which obviously didn't do what I would like it to do. I also don't want to use a loop because I am trying to make my script as simple as possible. ``` df = cbind(sort(rnorm(10)), sort(rnorm(10,-2)), sort(rlnorm(10))) plot(0, xlim = c(1,10), ylim=range(df), type="n") apply(df, 2, lines, type="b", col = c("red", "blue", "black")) ``` What I really want is a plot like below: ``` plot(0, xlim = c(1,10), ylim=range(df), type="n") color = c("red","blue","black") for(i in 1:3){ lines(1:10, df[,i], type = "b", col=color[i]) } ``` Thank you in advance!

Original source