0

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?

Brian Smith
  • 1,200
  • 4
  • 16
  • 1
    Does this answer your question? [ggplot2 shade area under density curve by group](https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group) – Adam Quek Jun 01 '22 at 05:55

1 Answers1

0

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