So far I have missed a histogram function with a fraction on the y-axis. Like this:
require(ggplot2)
data(diamonds)
idealD <- diamonds[diamonds[,"cut"]=="Ideal",]
fracHist <- function(x){
  frac <- (hist(x,plot=F)$counts) / (sum(hist(x,plot=F)$counts))
  barplot(frac)
}
### call
fracHist(idealD$carat)
It ain't pretty but basically should explain what I want: bar heights should add up to one. Plus the breaks should be labelling the x-axis. I'd love to create the same with ggplot2 but can't figure out how to get around plotting the frequencies offracinstead of plottingfracitself.
all I get with `ggplot` is density...
m <- ggplot(idealD, aes(x=carat)) 
m + geom_histogram(aes(y = ..density..)) + geom_density()
                The solution is to use stat_bin and map the aesthetic y=..count../sum(..count..)
library(ggplot2)
ggplot(idealD, aes(x=carat)) + stat_bin(aes(y=..count../sum(..count..)))
From a quick scan of ?hist I couldn't find how the values are binned in hist.  This means the graphs won't be identical unless you fiddle with the binwidth argument of stat_bin.

The trick works with geom_histogram histogram as well.
require(ggplot2)
data(diamonds)
idealD <- diamonds[diamonds[,"cut"]=="Ideal",]
ggplot(idealD, aes(x=carat))  +   geom_histogram(aes(y=..count../sum(..count..)))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With