Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Histogram with fraction in qplot / ggplot

Tags:

r

ggplot2

enter image description hereSo 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()
like image 264
Matt Bannert Avatar asked Oct 17 '11 07:10

Matt Bannert


2 Answers

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.

enter image description here

like image 96
Andrie Avatar answered Oct 07 '22 19:10

Andrie


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..)))

enter image description here

like image 41
DJJ Avatar answered Oct 07 '22 18:10

DJJ