Home > Back-end >  ggplot histogram with density plot that is filled with color
ggplot histogram with density plot that is filled with color

Time:06-01

I have below histogram with ggplot

library(ggplot2)
set.seed(1)
df <- data.frame(PF = 10*rnorm(1000))
ggplot(df, aes(x = PF))   
    geom_histogram(aes(y =..density..),
                   breaks = seq(-50, 50, by = 10), 
                   colour = "black", 
                   fill = "white")  
stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)))

Now I want to fill the normal density curve with some colour. I tried below without success

stat_function(fun = dnorm, args = list(mean = mean(df$PF), sd = sd(df$PF)), fill = 'red', alpha = 0.50)

Is there any way to apply fill colour the area under normal density curve?

CodePudding user response:

You could call stat_function() with a non-default geom (here: geom_ribbon) and access the y-value generated by stat_function with after_stat() like this:


## ...   
  stat_function(fun = dnorm,
                args = list(mean = mean(df$PF), sd = sd(df$PF)),              
                mapping = aes(x = PF, ymin = 0,
                              ymax = after_stat(y) ## see (1) 
                              ),
                geom = 'ribbon',
                alpha = .5, fill = 'blue'
                )

(1) on accessing computed variables (stats): https://ggplot2.tidyverse.org/reference/aes_eval.html

  • Related