Search code examples
rggplot2density-plot

What is the difference between position stack vs identity in ggplot?


Can someone explain the geom_density position option stack versus identity. Plots look very different but still overlap. What is fundamentally different between the two?


Solution

  • For some reason it is not explained in the geom_density help. However position="stack" stacks the values like this:

    enter image description here

    Whereas position="identity" overlays them like this:

    enter image description here

    Here is the code that generated those:

    n <- 1000
    A <- data.frame(id='A',x=rnorm(n, 5, 2))
    B <- data.frame(id='B',x=rexp(n, 1/4))
    C <- data.frame(id='C',x=rexp(n, 1/8))
    D <- data.frame(id='D',x=rexp(n, 1/16))
    df <- rbind(A,B,C,D)
    
    colorset = c('B'='red','A'='green','D'='black','C'='blue'  )
    
    ggplot(df, aes(x)) +
      geom_density(aes(fill = id), alpha = .4, adjust = 2,position="stack") +
      scale_fill_manual(values=colorset) +
      scale_x_continuous( limits =c(0,40)) + labs(title="geom_density: position=`Stack`")
    
    ggplot(df, aes(x)) +
      geom_density(aes(fill = id), alpha = .4, adjust = 2,position="identity") +
      scale_fill_manual(values=colorset) +
      scale_x_continuous( limits =c(0,40)) + labs(title="geom_density: position=`identity`")