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

时间:2019-08-09 13:16:02

标签: r ggplot2 plot frequency lattice

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

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)

但是它不能那样工作。我应该在代码中更改什么?对我来说,在图形之前计算相对频率不是一个选择。

2 个答案:

答案 0 :(得分:3)

您需要直方图,而不是条形图,所以:

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

lattice

enter image description here

ggplot2

enter image description here

您会看到,两种算法的分箱算法工作稍有不同。

答案 1 :(得分:-1)

您可以尝试类似:

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