8

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
neringab
  • 613
  • 1
  • 7
  • 16

2 Answers2

24

You want a histogram, not a barplot, so:

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

lattice:

enter image description here

ggplot2:

enter image description here

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

Axeman
  • 32,068
  • 8
  • 81
  • 94
0

You can try something like :

ggplot(data=df, aes(x=a)) + geom_bar(aes(y = (..count..)/sum(..count..)), group = 1)
S.Gradit
  • 164
  • 1
  • 9