rggplot2plotdensity-plot

Averaging multiple density curves in plot


I would like to get only one curve that is the "average" of all curves in order to get the "average trend". In my specific case, it is to average simulations I made.

Using this tutorial (cf the code below) , I managed to get multiple curves like this :

enter image description here

Here is the code to get the plot above :

set.seed(06062023)
my_values = list(rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10),
                      rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10))

den<-lapply(my_values, density)
plot(den[[1]], ylim=c(0,0.8), xlim=c(-6,6),main='Densities altogether') 
for(i in 2:length(den)){        
  lines(den[[i]], col=i)        
}

Solution

  • We can use approx to get esimates from the densities at a consisted grid and then take the average over those values. For example

    z <- seq(-6, 6, length.out=100)
    zavg <- rowMeans(sapply(den, function(d) approx(d$x, d$y, z, yleft=0, yright=0)$y))
    lines(z, zavg, col="red", lwd=3)
    

    This creates the think red line on the plot enter image description here