R中两个样本的密度比较和虚拟化

时间:2013-02-03 18:10:26

标签: r pdf

我必须比较R中两个样本的密度函数。令人惊讶的是,无论我使用的函数,plot(),lines()还是ggplot,两个样本中的一个都没有出现,或者两个区域都不同,不能等于一。我希望两个区域在同一图表上相等,以便容易地确定样本的pdf大于另一个的pdf的横坐标值集合。我该如何解决?非常感谢你的帮助。

1 /使用ggplot,脚本为:

require ("ggplot2")
p2<-density(tabgroupcl2$B, n=1000)
p1<-density(tabgroupcl1$B, n=1000)
dat <- data.frame(dens = c(p1$x, p2$x)
                   , lines = rep(c("cl1", "cl2")), each=1000)
ggplot(dat,aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)

2 /密度(tabgroupcl2 $ B):

Call:
        density.default(x = tabgroupcl2$B)

Data: tabgroupcl2$B (348 obs.); Bandwidth 'bw' = 0.001689

       x                y           
 Min.   :-91.95   Min.   :  0.0000  
 1st Qu.:-34.07   1st Qu.:  0.0000  
 Median : 23.80   Median :  0.0000  
 Mean   : 23.80   Mean   :  0.4613  
 3rd Qu.: 81.68   3rd Qu.:  0.0000  
 Max.   :139.56   Max.   :179.2431  

3 /密度(tabgroupcl1 $ B):

Call:
        density.default(x = tabgroupcl1$B)

Data: tabgroupcl1$B (9 obs.);   Bandwidth 'bw' = 0.2738

       x                y            
 Min.   :-2.607   Min.   :0.0000000  
 1st Qu.: 1.495   1st Qu.:0.0000000  
 Median : 5.598   Median :0.0001349  
 Mean   : 5.598   Mean   :0.0608673  
 3rd Qu.: 9.700   3rd Qu.:0.0548682  
 Max.   :13.802   Max.   :0.7583033

3 个答案:

答案 0 :(得分:1)

看起来您正在使用ggplot()函数中密度对象的x值,就好像它们是原始数据一样。我不明白你为什么要这样做,但如果是这样你也需要使用y值 - 而你根本不需要ggplot中的密度stat。或者,让密度统计工作并使用原始数据。

答案 1 :(得分:0)

彼得埃利斯的回答是完全正确的。这是一个“基础”示例,说明如何估算和绘制同一轴上两个不同样本的密度:

x <- rnorm(1000, mean=3, sd=2)
y <- rnorm(500, mean=3.5, sd=3)

dx <- density(x)
dy <- density(y)

plot.new()
plot.window(xlim=range(c(dx$x, dy$x)), ylim=range(c(dx$y, dy$y)))
with(dx, lines(x, y))
with(dy, lines(x, y, lty=2))
axis(1)
axis(2)
legend(topright, lty=1:2, c('x', 'y'))
mtext(side=1, line=2, 'Observed values')
mtext(side=2, line=2, 'Estimated probability mass')
title('Smoothed Density Estimates for 2-sample experiment')

答案 2 :(得分:0)

enter image description here这就是我在一个图中叠加两个数据集列的方法:

这里我在每个数据框中创建一个新列(samediff),并在列中重复文本以识别它。 same_auditor$samediff <- "same" diff_auditor$samediff <- "diff"

组合绘图的数据集。 samescore <- same_auditor$Audit_Score diffscore <- diff_auditor$Audit_Score sameDiffcombined <- rbind(diff_auditor,same_auditor)

ggplot(sameDiffcombined, aes(Audit_Score, fill = samediff)) + geom_density(alpha = 0.5)