重叠堆积密度图

时间:2014-08-15 14:43:32

标签: r plot probability-density density-plot stacked-chart

我正在尝试使用R的原生情节命令来实现与此类似的情节。

enter image description here

我能够得到类似下面代码的东西,但是,我希望密度多边形重叠。任何人都可以建议一种方法吗?

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)
}

输出:

enter image description here

2 个答案:

答案 0 :(得分:4)

我会这样做,如下所示。我在同一个图中绘制密度,但是在y值上添加一个整数。为了使它们重叠,我乘以常数因子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

答案 1 :(得分:0)

(注意:此内容以前已编入问题,由@by0撰写。)

感谢@AEBilgrau,我很快将这个功能放在一起,这个功能非常好用。注意:您需要使用系数fac,具体取决于您的数据。

stacked.density <- function(data, fac = 3, xlim, col = 'black', 
                            alpha = 0.4, show.xaxis = T, 
                            xlab = '', ylab = ''){
  xvals = unlist(lapply(data, function(d) d$x))
  if(missing(xlim)) xlim=c(min(xvals), max(xvals))

  col = sapply(col, col2alpha, alpha)
  if(length(col) == 1) col = rep(col, length(data))

  plot(1, type = "n", xlim = xlim, ylim = c(1,length(data) + 2),
       yaxt='n', bty='n', xaxt=ifelse(show.xaxis, 'l', 'n'), xlab = xlab, ylab = ylab)

  z = length(data):1
  for(i in 1:length(data)){
    d = data[[ z[i] ]]
    lines(d$x, fac*d$y + i, lwd=1)
    polygon(d$x, fac*d$y+ i, col=col[i], border=NA)
    abline(h = i, lwd=0.5)
  }
}

data <- lapply(1:5, function(x) density(rnorm(100, mean = x)))
stacked.density(data, col=c('red', 'purple', 'blue', 'green', 'yellow'), alpha=0.3, show.xaxis=T)

输出:

enter image description here