Normalizing y-axis in histograms in R ggplot to proportion by group

后端 未结 1 437
無奈伤痛
無奈伤痛 2020-12-04 14:18

My question is very similar to Normalizing y-axis in histograms in R ggplot to proportion, except that I have two groups of data of different size, and I would like that eac

相关标签:
1条回答
  • 2020-12-04 14:54

    Like this? [edited based on OP's comment]

    ggplot(all,aes(x=value,fill=dataset))+
      geom_histogram(aes(y=0.5*..density..),
                     alpha=0.5,position='identity',binwidth=0.5)
    

    Using y=..density.. scales the histograms so the area under each is 1, or sum(binwidth*y)=1. As a result, you would use y = binwidth*..density.. to have y represent the fraction of the total in each bin. In your case, binwidth=0.5.

    IMO this is a little easier to interpret:

    ggplot(all,aes(x=value,fill=dataset))+
      geom_histogram(aes(y=0.5*..density..),binwidth=0.5)+
      facet_wrap(~dataset,nrow=2)
    
    0 讨论(0)
提交回复
热议问题