0

For my thesis I need to plot a histogram of several variables and I want to add a dnorm curve to it. Unfortunately, it doesn't work. oes_scale is a standardized variable.

ggplot(data, aes(oes_scale)) +
  geom_histogram(binwidth = 0.35, fill = "darkgrey", color = "black") +
  xlim(-2.5, 3) +
  ylim(0, 70) +
  labs(x="Soziale Ausgrenzung", y="Häufigkeit") +
  stat_function(fun = dnorm, args = list(mean = mean(data$oes_scale), sd = sd(data$oes_scale)), color = "black", size = 1) +
  theme_apa(legend.font.size = 11)

I tried this but the curve seems to be very wide. I have tried several things, which all haven't worked. I tried to get the relative frequencies with

ggplot(data, aes(x = oes_scale, y = ..density.. * 0.35)) +
  geom_histogram(binwidth = 0.35, fill = "darkgrey", color = "black") +
  xlim(-2, 3) +
  ylim(0, 0.25) +
  stat_function(fun = ~dnorm(.x, mean = mean(data$oes_scale), sd = sd(data$oes_scale))) +
  labs(x = "Soziale Ausgrenzung", y = "Relative Häufigkeit") +
  theme_apa(legend.font.size = 11)

which worked without the stat_function but when I try to add it to the plot, I get this message:

Error in stat_function(): ! Problem while mapping stat to aesthetics. ℹ Error occurred in the 2nd layer. Caused by error in density * 0.35: ! non-numeric argument to binary operator Backtrace:

  1. base (local) <fn>(x)
  2. ggplot2:::print.ggplot(x)
  3. ggplot2:::ggplot_build.ggplot(x)
  4. ggplot2:::by_layer(...)
  5. ggplot2 (local) f(l = layers[[i]], d = data[[i]])
  6. l$map_statistic(d, plot)
  7. ggplot2 (local) map_statistic(..., self = self)
  8. base::lapply(new, eval_tidy, mask, env)
  9. rlang (local) FUN(X[[i]], ...) Warning message: Removed 6 rows containing non-finite values (stat_bin()).

Does anyone have any tips on what I could try?

Thank you in advance! :)

hr1211
  • 1
  • Have you looked at https://stackoverflow.com/questions/6967664/ggplot2-histogram-with-normal-curve ? Can you explain why your situation is different from this question? – Allan Cameron Jul 18 '23 at 19:32
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Jul 18 '23 at 19:40

0 Answers0