ggplot2 geom_density and geom_histrogram in one plot

前端 未结 1 1813
无人及你
无人及你 2021-01-28 09:37

How can I make a histogram in which all bars add up to 1 and add a density layer above that fits?

set.seed(1234)
df <- data.frame(
  sex=factor(rep(c(\"F\", \         


        
相关标签:
1条回答
  • 2021-01-28 10:17

    Try using y = ..density../sum(..density..):

    set.seed(1234)
    df <- data.frame(
        sex=factor(rep(c("F", "M"), each=200)),
        weight=round(c(rnorm(200, mean=55, sd=5),
                       rnorm(200, mean=65, sd=5)))
    )
    
    library(ggplot2)
    
    ggplot(df, aes(x=weight, color=sex, fill=sex)) + 
        geom_histogram(aes(y=..density../sum(..density..)), alpha=0.5, 
                       position="identity")+
        geom_density(alpha=.2)
    
    0 讨论(0)
提交回复
热议问题