“Density” curve overlay on histogram where vertical axis is frequency (aka count) or relative frequency?

后端 未结 3 1924
青春惊慌失措
青春惊慌失措 2020-11-29 04:59

Is there a method to overlay something analogous to a density curve when the vertical axis is frequency or relative frequency? (Not an actual density function, since the ar

3条回答
  •  感情败类
    2020-11-29 05:35

    library(ggplot2)
    smoothedHistogram <- function(dat, y, bins=30, xlabel = y, ...){
      gg <- ggplot(dat, aes_string(y)) + 
        geom_histogram(bins=bins, center = 0.5, stat="bin", 
                       fill = I("midnightblue"), color = "#E07102", alpha=0.8) 
      gg_build <- ggplot_build(gg)
      area <- sum(with(gg_build[["data"]][[1]], y*(xmax - xmin)))
      gg <- gg + 
        stat_density(aes(y=..density..*area), 
                     color="#BCBD22", size=2, geom="line", ...)
      gg$layers <- gg$layers[2:1]
      gg + xlab(xlabel) +  
        theme_bw() + theme(axis.title = element_text(size = 16),
                           axis.text = element_text(size = 12))
    }
    

    dat <- data.frame(x = rnorm(10000))
    smoothedHistogram(dat, "x")
    

提交回复
热议问题