【发布时间】:2011-11-11 14:04:51
【问题描述】:
如何使用 R 中的 hist() 函数绘制百分比而不是原始频率?
【问题讨论】:
-
@alvas,为什么?布赖恩的答案正是我想要的。
如何使用 R 中的 hist() 函数绘制百分比而不是原始频率?
【问题讨论】:
仅使用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)
您所做的基本上是创建一个直方图对象,将密度属性更改为百分比,然后重新绘制。
【讨论】:
如果您想在 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)")
# 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)")
【讨论】: