2010-11-01 93 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