12

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!

13
  • 2
    Try y = ..density...
    – joran
    May 2, 2013 at 13:55
  • 1
    all has to be a dataframe. Try all <- as.data.frame(cbind(hvalues,season,year)). May 2, 2013 at 13:57
  • 1
    @JT85 I agree, but please don't encourage the use of as.data.frame(cbind(...)) in place of data.frame(...).
    – joran
    May 2, 2013 at 14:03
  • 2
    Check out ?stat_bin and try the options there. I think maybe ..ncount.. is what you're looking for.
    – joran
    May 2, 2013 at 15:36
  • 1
    Sigh. Exactly. Scaling to 1 in each facet is precisely what you said you want. I'm moving on now.
    – joran
    May 2, 2013 at 15:44

1 Answer 1

13

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.

1
  • Does anyone know what docs describe ..PANEL..? I see count etc listed in ?stat_bin under "Computed Variables" section, but I don't know how to even start searching for help on PANEL. Also, this is neat. Nov 8, 2022 at 6:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.