像流式细胞术一样堆积直方图 [英] Stacked histograms like in flow cytometry

查看:178
本文介绍了像流式细胞术一样堆积直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot或base R来生成类似以下的内容:

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

我知道如何使用ggplot2做直方图,并且可以使用facet_grid或facet_wrap轻松地将它们分开.但我想垂直交错"它们,以使它们有些重叠,如下所示.抱歉,我不允许发布自己的图片,而且很难找到我想要的简单图片.如果可以的话,我只会发布左上方的面板.

I know how to do histograms with ggplot2, and can easily separate them using facet_grid or facet_wrap. But I'd like to "stagger" them vertically, such that they have some overlap, as shown below. Sorry, I'm not allowed to post my own image, and it's quite difficult to find a simpler picture of what I want. If I could, I would only post the top-left panel.

我知道这不是一种显示数据的特别好方法-但这决定并不取决于我.

I understand that this is not a particularly good way to display data -- but that decision does not rest with me.

样本数据集如下:

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

我可以使用geom_histogram对其进行绘制,如下所示:

And I can plot it with geom_histogram as follows:

ggplot(my.data) + geom_histogram(aes(x=V1,fill=as.factor(V2))) + facet_grid( V2~.)

但是我希望y轴重叠.

推荐答案

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)

根据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"]])
})

根据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

并绘制

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)

这篇关于像流式细胞术一样堆积直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆