具有密度拟合的直方图和用频率标记的条

时间:2014-08-28 11:34:38

标签: r histogram probability frequency

我想显示直方图的概率,密度曲线拟合,以及计数标记的条形。下面的代码生成两个数字,顶部显示频率条(用频率标记)和密度曲线。底部显示了密度曲线的概率条(用概率标记)。我想要的是频率标记的概率条,因此我们可以读取概率和频率。或者,我想要第二个情节,第一个情节中的条形标签。

coeff_value = c(6.32957806, 3.04396650, 0.02487562, 3.50699592, 5.03952569, 3.05907173, 
0.41095890, 1.88648325, 5.04250569, 0.89320388, 0.83732057, 1.12033195, 
2.35697101, 0.58695652, 4.83363583, 7.91154791, 7.99614644, 9.58737864, 
1.27358491, 1.03938247, 8.66028708, 6.32458234, 3.85263158, 1.37299546, 
0.53639847, 7.63614043, 0.51502146, 9.86557280, 0.60728745, 3.00613232, 
6.46573393, 2.60848869, 2.34273319, 1.82448037, 6.36600884, 0.70043777, 
1.47600793, 0.42510121, 2.58064516, 3.45377741, 6.29475205, 4.97536946, 
2.24637681, 2.12000000, 1.92792793, 0.97613883, 6.01214190, 4.47316103, 
1.87272727, 10.08896797, 0.09049774, 1.93779904, 6.53444676, 3.46590909, 
6.52730822, 7.23229671, 4.91740279, 5.24545125)
h=hist(coeff_value,plot=F,freq=T,breaks=10)
h$density = h$density*100
par(mfrow=c(2,1)) 
plt=plot(h, freq=T, main="Freq = T",xlab="rate", 
       ylab="Frequency", xlim=c(0, 20), ylim=c(0, 30),
       col="gray", labels = TRUE)
densF=density(coeff_value)
lines(densF$x, densF$y*length(coeff_value), lwd=2, col='green') 
plt=plot(h, freq=F, main="Freq = F",xlab="rate", 
       ylab="Probability (%)", xlim=c(0, 20), ylim=c(0, 30),
       col="gray", labels = TRUE)
densF=density(coeff_value)
lines(densF$x, densF$y*100, lwd=2, col='green') 

paste("bar sum =",sum(h$density))
paste("line integral =",sum((densF$y[-length(densF$y)]*100)*diff(densF$x)))

1 个答案:

答案 0 :(得分:3)

只需绘制直方图并捕获输出(在绘图之前,您仍然需要将密度乘以100才能得到%):

h <- hist(coeff_value,plot=F,breaks=10)
h$density <- h$density*100
plot(h, freq=F, xlab="rate", 
       ylab="Probability (%)", ylim=c(0, 25),
       col="gray")
densF <- density(coeff_value)
lines(densF$x, densF$y*100, lwd=2, col='green') 

现在h包含您需要的所有信息:

text(h$mids,h$density,h$counts,pos=3)

histogram with density and counts