R中的相对频率直方图,ggplot

Relative frequency histogram in R, ggplot

我可以在 R 中绘制相对频率直方图,使用 lattice 包:

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

我想在 ggplot 中获得相同的图表。我试过了

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

但事实并非如此。我应该在代码中更改什么?在图表之前计算相对频率对我来说不是一个选项。

您可以尝试类似的方法:

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

您需要直方图,而不是条形图,因此:

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

lattice:

ggplot2:

您可以看到两个包的装箱算法略有不同。