by0 by0 -4 years ago 120
R Question

Overlapping stacked density plots

I'm trying to achieve a similar plot to this one, using R's native plot command.

enter image description here

I was able to get something similar with the code below, however, I'd like the density polygons to overlap. Can anyone suggest a way to do this?

data = lapply(1:5, function(x) density(rnorm(100, mean = x)))

par(mfrow=c(5,1))
for(i in 1:length(data)){
plot(data[[i]], xaxt='n', yaxt='n', main='', xlim=c(-2, 8), xlab='', ylab='', bty='n', lwd=1)
polygon(data[[i]], col=rgb(0,0,0,.4), border=NA)
abline(h=0, lwd=0.5)
}


Outputs:

enter image description here

Answer Source

I would do it something like the following. I plot the densities in the same plot but add an integer to the y values. To make them overlapping i multiply by a constant factor fac.

# Create your toy data
data <- lapply(1:5, function(x) density(rnorm(100, mean = x)))

fac <- 5  # A factor to make the densities overlap

# We make a empty plot
plot(1, type = "n", xlim = c(-3, 10), ylim = c(1, length(data) + 2),
     axes = FALSE, xlab = "", ylab = "")  

# Add each density, shifted by i and scaled by fac
for(i in 1:length(data)){
  lines(  data[[i]]$x, fac*data[[i]]$y + i)
  polygon(data[[i]]$x, fac*data[[i]]$y + i, col = rgb(0, 0, 0, 0.4), border = NA)
  abline(h = i, lwd = 0.5)
}

Output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download