2011-09-06 96 views

回答

64

只需使用freq=FALSE参数不给人以百分比的柱状图,它规范了直方图所以总面积等于1
为了得到一些数据集的百分比的直方图,说X,这样做:

h = hist(x) 
h$density = h$counts/sum(h$counts)*100 
plot(h,freq=FALSE) 

基本上你正在做的是创建一个直方图对象,将密度属性更改为百分比,然后重新绘图。

+4

非常好。我建议改变y轴标签:plot(h,freq = F,ylab ='Percentage') – PeterVermont

1

如果你想明确地列出x在x轴的每一个值(即绘制一个整数变量,如计数的百分比),那么下面的命令是一个更方便的选择:

# Make up some data 
set.seed(1) 
x <- rgeom(100, 0.2) 

# One barplot command to get histogram of x 
barplot(height = table(factor(x, levels=min(x):max(x)))/length(x), 
     ylab = "proportion", 
     xlab = "values", 
     main = "histogram of x (proportions)") 

enter image description here

# Comparison to hist() function 
h = hist(x, breaks=(min(x)-1):(max(x))+0.5) 
h$density = h$counts/sum(h$counts)*100 
plot(h,freq=FALSE, main = "histogram of x (proportions)") 

enter image description here