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:
- base (local)
<fn>
(x) - ggplot2:::print.ggplot(x)
- ggplot2:::ggplot_build.ggplot(x)
- ggplot2:::by_layer(...)
- ggplot2 (local) f(l = layers[[i]], d = data[[i]])
- l$map_statistic(d, plot)
- ggplot2 (local) map_statistic(..., self = self)
- base::lapply(new, eval_tidy, mask, env)
- 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! :)