2015-06-26 156 views
2

我有一個向量(變量dist),我想繪製一個7單位的bin-width的直方圖。下面是分配給dist如何用概率y軸而不是密度y軸創建直方圖?

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

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

它創建這個圖形:到目前爲止

enter image description here

,那麼好。 0到6之間有三個數字,7到13之間有兩個數字,如直方圖所示。

現在,我使用hist與創建如下圖的prop=TRUE參數:

enter image description here

而是在y軸上的密度,我想它顯示了倉的概率。例如,通過27與值21的bin具有0.02304147的高度(或密度),計算如下:

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

這可以通過畫線與該高度進行驗證:

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

其中提請

enter image description here

然而,我想在y軸上,顯示概率爲一些落入21〜27箱,這是

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

0.1612930

這是可能以某種方式?

回答

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

您可以通過直方圖中斷來組合羣組並製作條形圖。

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