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

前提是你 提交于 2020-01-02 06:15:47

问题


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!

回答1:


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



来源:https://stackoverflow.com/questions/10668221/apply-lines-to-columns-of-a-data-frame-matrix-each-line-with-a-different-colo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!