Stacked histograms like in flow cytometry

前端 未结 5 1223
攒了一身酷
攒了一身酷 2020-12-15 14:45

I\'m trying to use ggplot or base R to produce something like the following:

\"enter

5条回答
  •  Happy的楠姐
    2020-12-15 14:58

    require(ggplot2)
    require(plyr)
    
    my.data <- as.data.frame(rbind( cbind( rnorm(1e3), 1) , cbind(     rnorm(1e3)+2, 2), cbind( rnorm(1e3)+3, 3), cbind( rnorm(1e3)+4, 4)))
    my.data$V2=as.factor(my.data$V2)
    

    calculate the density depending on V2

    res <- dlply(my.data, .(V2), function(x) density(x$V1))
    dd <- ldply(res, function(z){
      data.frame(Values = z[["x"]], 
                 V1_density = z[["y"]],
                 V1_count = z[["y"]]*z[["n"]])
    })
    

    add an offset depending on V2

    dd$offest=-as.numeric(dd$V2)*0.2 # adapt the 0.2 value as you need
    dd$V1_density_offest=dd$V1_density+dd$offest
    

    and plot

    ggplot(dd, aes(Values, V1_density_offest, color=V2)) + 
      geom_line()+
      geom_ribbon(aes(Values, ymin=offest,ymax=V1_density_offest,     fill=V2),alpha=0.3)+
      scale_y_continuous(breaks=NULL)
    

    results

提交回复
热议问题