Overlay normal curve to histogram in R

I would like to draw a line overlaying the normal curve to below histogram
however it doesn´t work. I don´t understand where is the problem. thanks in advance! :slight_smile:

{r Load libraries}
library(fpp3)
{r tidy data}
A_Beer_production <- aus_production %>% select(Quarter:Beer)
{r set training period}

B_Set_training_period <- A_Beer_production %>% 
   filter_index("1992 Q1" ~ "2007 Q4")

{r Residuals Seasonal Naive method}
Residuals_SNAIVE <- B_Set_training_period %>% model(SNAIVE(Beer)) %>% augment()
{r ggplot}

ggplot(Residuals_SNAIVE, aes(x=.resid)) +
  geom_histogram(aes(y = ..density..), fill='lightgray', col='black') +
  stat_function(fun = dnorm, args = list(mean=mean(Residuals_SNAIVE$.resid), sd=sd(Residuals_SNAIVE$.resid)))

thanks in advance

Hi @Tony_iberian ,

Running your code throws a ggplot error referring to data out-of-limits. Inspecting the data revealed NA present in the residuals. Hence add .., na.rm = TRUE to both the mean() and sd() calls.

So When you replace

with mean = mean(Residuals_SNAIVE$.resid, na.rm = TRUE) and likewise for the sd = sd(..., na.rm=TRUE) you'll probably be fine. At least I was :slight_smile:

Good luck,

JW

1 Like

that´s perfect! Many thanks for your help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.