Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing faceted histograms separately in ggplot2

My questions is similar to Normalizing y-axis in histograms in R ggplot to proportion but I'd like to add to it a bit.

In general, I have 6 histograms in a 2x3 facet design, and I'd like to normalize each of them separately. I'll try to make a sample data set here to give an idea:

hvalues=c(3,1,3,2,2,5,1,1,12,1,4,3)
season=c("fall","fall","fall","fall","winter","winter","winter","winter","summer","summer","summer","summer")
year=c("year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2")
group=c("fall year 1","fall year 1","fall year 2","fall year 2","winter year 1","winter year 1","winter year 2","winter year 2","summer year 1","summer year 1","summer year 2","summer year 2")
all=data.frame(hvalues,season,year)

Using

ggplot(all, aes(x=hvalues,group=group)) + 
geom_histogram(aes(y=..count../sum(..count..))) + 
facet_grid(season ~ year)

gives the proportions overall (i.e. combining all the facets). I'd like each group facet to be normalized to 1. hvalues are not integers in my actual data - they are numerical.

I am a novice using R, and would really appreciate some help. Thanks in advance!

like image 452
user1195564 Avatar asked May 02 '13 13:05

user1195564


1 Answers

The solution is:

ggplot(all, aes(x=hvalues)) +
    facet_grid(season ~ year,drop=T) +
    geom_histogram(aes(y=(..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..]))

I stole this from this question

I feel your question might be a duplicate of that one by the way.

like image 63
stacksia Avatar answered Nov 14 '22 02:11

stacksia