使用R中的hist()函数获得百分比而不是原始频率

new*_*v14 26 r histogram

如何使用R中的hist()函数绘制百分比而不是原始频率?

小智 86

简单地使用freq=FALSE参数不会给出百分比的直方图,它会对直方图进行标准化,因此总面积等于1.
要获得某些数据集的百分比直方图,比如x,请执行以下操作:

h = hist(x) # or hist(x,plot=FALSE) to avoid the plot of the histogram
h$density = h$counts/sum(h$counts)*100
plot(h,freq=FALSE)
Run Code Online (Sandbox Code Playgroud)

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

  • 非常好.我建议更改y轴标签:plot(h,freq = F,ylab ='Percentage') (8认同)

maj*_*jom 5

如果要显式列出xx轴上的每个单个值(即,绘制整数变量的百分比,如计数),则以下命令是更方便的选择:

# 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)")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

# 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)")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明