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!

4

1 回答 1

12

解决方案是:

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

我从这个问题中偷了这个

顺便说一句,我觉得你的问题可能与那个问题重复。

于 2014-07-19T21:23:11.780 回答