如何创建概率为y轴而不是密度为y轴的直方图?

时间:2015-06-26 19:07:06

标签: r histogram

我有一个向量(变量strtol),我想要绘制一个bin宽度为7个单位的直方图。这是dist的作业:

dist

为了绘制直方图,我使用dist <- c( # 0-6 7-13 14-20 21-27 28-34 35-41 42-48 49-55 # --- ---- ----- ----- ----- ----- ----- ----- 16, 20, 29, 17, 27, 28, 19, 21, 34, 3, 14, 26, 33, 35, 44, 1, 11, 14, 21, 29, 38, 43, 55, 4, 12, 18, 22, 32, 35, 48, 50 )

hist

创建此图形:

enter image description here

到目前为止,这么好。在0和6之间有三个数字,在7和13之间有两个数字,依此类推,如直方图所示。

现在,我使用hist(dist, breaks=seq(0, 56, by=7)-0.5) hist参数创建了以下图表:

enter image description here

而不是y轴上的密度,我希望它显示bin的概率。例如,值为21到27的bin的高度(或密度)为0.02304147,计算方法如下:

prop=TRUE

这可以通过绘制具有此高度的线来验证:

dens_21_27 <- length(dist[dist > 20.5 & dist < 27.5])/length(dist)/7

绘制

enter image description here

然而,我希望y轴显示一个数字落入21到27 bin的概率,这是

lines(c(-5, 56), c(dens_21_27, dens_21_27), col="#FF770070")

length(dist[dist > 20.5 & dist < 27.5])/length(dist)

这有可能吗?

2 个答案:

答案 0 :(得分:2)

这是我过去用来强迫概率值的包装纸。

probabilityplot<-function(x, ..., prob=T, ylab="Probability") {
    xx<-hist(x, yaxt="n", prob=prob, ylab=ylab , ...)
    bin.sizes<-diff(xx$breaks)
    if (any(bin.sizes != bin.sizes[1])) stop("bin sizes are not the same")
    marks<-axTicks(2)
    axis(2, at=marks, labels=marks*bin.sizes[1])
    xx$probabilities <- xx$density*bin.sizes[1]
    invisible(xx)
}

probabilityplot(dist,breaks=seq(0, 56, by=7)-0.5 )

enter image description here

设计直方图以估计连续随机变量的密度,因此优先考虑密度超过概率。

答案 1 :(得分:1)

您可以通过直方图中断对组进行分组并制作条形图。

bs <- hist(dist, breaks=seq(0, 56, by=7)-0.5, plot=F)$breaks
probs <- table(cut(dist, bs)) / length(dist)
barplot(probs, ylab="Probability", las=2)

enter image description here