Relative frequency histogram in R, ggplot

与世无争的帅哥 提交于 2021-02-08 08:16:08

问题


I can draw relative frequency histogram in R, using lattice package:

a <- runif(100)
library(lattice)
histogram(a)

I want to get the same graph in ggplot. I tried

dt <- data.frame(a)
ggplot(dt, aes(x = a)) + 
geom_bar(aes(y = ..prop..))+
 scale_y_continuous(labels=percent)

but it doesn't work like that. What I should change in the code? Calculating relative frequency before graph is not an option for me.


回答1:


You want a histogram, not a barplot, so:

ggplot(dt, aes(x = a)) + 
  geom_histogram(aes(y = stat(count) / sum(count)), bins = 8) +
  scale_y_continuous(labels = scales::percent)

lattice:

ggplot2:

You can see that the binning algorithm works slightly different for the two packages.




回答2:


You can try something like :

ggplot(data=df, aes(x=a)) + geom_bar(aes(y = (..count..)/sum(..count..)), group = 1)


来源:https://stackoverflow.com/questions/57430885/relative-frequency-histogram-in-r-ggplot

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