0

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.

changeR
  • 37
  • 1
  • 5
  • It would be helpful if you could provide us with a reproducible [minimal working example](https://en.wikipedia.org/wiki/Minimal_working_example) that we can copy and paste to better understand the issue and test possible solutions. You can share datasets with `dput(YOUR_DATASET)` or smaller samples with `dput(head(YOUR_DATASET))`. (See [this answer](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610) for some great advice.) – ktiu Jun 20 '21 at 12:39

2 Answers2

1

For example this,

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

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

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

}

gives,

enter image description here

Fake Data:

df <-data.frame( matrix(rnorm(1000),ncol=10))
maydin
  • 3,715
  • 3
  • 10
  • 27
0

First the vector in the loop argument should be 1:length(dfff). The first desity plot should be made by calling the function plot. The sunsequent density plots can be made by calling lines. You can add col argument for differentiating by colours.

for (i in 1:length(dfff)) {
  x <- dfff[,i]
  if(i == 1){
    plot(density(x))
  } else{
    lines(density(x), col = i)
  }
  
}

enter image description here

Mohanasundaram
  • 2,889
  • 1
  • 8
  • 18