首页 > 解决方案 > Creating overlay plots with a loop in r

问题描述

Hey guys I hope someone can help me out. I want to make a loop that gives me an overlapping density plot. I have tried the following...

for (i in length(df)) {
  x <- df[,i]
  plot(density(x))
  lines(density(x ))
}

However, this only gives me a plot with one density line. But in my case it should be 100 density lines overlapping in one plot.

标签: rplot

解决方案


例如这个,

for (i in 1:length(df)) {
  x <- df[,i]

  if(i==1) {    
 
   plot(density(x),col=i)   

  }else {
  lines(density(x),col=i)
  }

}

给,

在此处输入图像描述

假数据:

df <-data.frame( matrix(rnorm(1000),ncol=10))

推荐阅读