Use hist() function in R to get percentages as opposed to raw frequencies

佐手、 提交于 2019-12-17 18:03:27

问题


How can one plot the percentages as opposed to raw frequencies using the hist() function in R?


回答1:


Simply using the freq=FALSE argument does not give a histogram with percentages, it normalizes the histogram so the total area equals 1.
To get a histogram of percentages of some data set, say x, do:

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)

Basically what you are doing is creating a histogram object, changing the density property to be percentages, and then re-plotting.




回答2:


If you want explicitly to list every single value of x on the x-axis (i.e. to plot the percentages of a integer variable such as counts), then the following command is a more convenient alternative:

# 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)")



来源:https://stackoverflow.com/questions/7324683/use-hist-function-in-r-to-get-percentages-as-opposed-to-raw-frequencies

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!