2010-11-01 83 views
13

你如何使用hist()來繪製R中的相對頻率?你如何使用hist來繪製R中的相對頻率?

如果我這樣做時,我會得到一個密度圖,但我希望有一個相對頻率圖:

a <- c(0,0,0,1,1,2) 
hist(a, freq=FALSE) 

我想看到下面的相對頻率直方圖:

0.5爲0至1,

0.33爲1至2,

和0.166爲2〜3。

+0

顯然你不能使用頻率= TRUE與劇情= FALSE,所以這是下面一些好的答案一個很好的問題,謝謝。 – PatrickT 2013-11-13 06:47:05

+0

[在R中使用hist()函數來獲取百分比而不是原始頻率]可能的副本(http://stackoverflow.com/questions/7324683/use-hist-function-in-r-to-get-percentages-與原始頻率相反) – majom 2016-08-05 14:40:12

回答

13

你可以嘗試使用histogram()功能晶格

a <- c(0,0,0,1,1,2) 
library(lattice) 
histogram(a) 

默認爲個百分點。

+1

很可惜,它使用如此醜陋的顏色作爲默認值:) – zoltanctoth 2011-08-06 01:35:59

6
hist(a, breaks=c(0, 1, 2, 3), freq=FALSE, right=FALSE) 
2

不正確傳統直方圖...

h<-hist(yourdata) 
plot(h$mids,100*h$counts/sum(h$counts),type="h") 
1
histo<-hist(yourvariable) 
barplot(histo$counts/n,col="white",space=0)->bp # n=length(yourvariable) 
axis(1,at=c(bp),labels=histo$mids) 
title(ylab="Relative Frequency",xlab="Your Variable Name") 
7

我添加了一個新功能的HistogramTools包上CRAN,PlotRelativeFrequency()這需要一個柱狀圖對象,並生成一個相對頻率直方圖。現在可從R-Forge購買,並將在下一個CRAN版本的HistogramTools 0.3中提供。

基本上,您只需要對R中的默認直方圖進行兩次修改。首先,您需要將每個計數除以所有計數的總和,並且您需要替換y軸標籤以注意現在正在繪製相對頻率。

x<-runif(100) 
h<-hist(x, plot=F) 
h$counts <- h$counts/sum(h$counts) 
plot(h, freq=TRUE, ylab="Relative Frequency") 

或者,乾脆

install.packages("HistogramTools", repos="http://R-Forge.R-project.org") 
library(HistogramTools) 
PlotRelativeFrequency(hist(x, plot=F)) 

enter image description here