Context: I have some data, and I wish to:
- plot a histogram of them
- add a kernel density
- add a "theoretical density"
- add a legend to distinguish between 2. and 3.
Consider:
X <- rnorm(1000,0,1)
Y <- (X^2-1)/2
ggplot(as.data.frame(Y), aes(x=Y)) +
geom_histogram(aes(y=..density..),
binwidth=.2,
colour="black", fill="white") +
geom_density(alpha=.2, fill="#FF6666")

This accomplishes 1. and 2., but how can I achieve 3. and 4.? I have written the function I wish to plot:
myfunc <- function(x) {
2*exp(-x-0.5)/(sqrt(2*x+1)*sqrt(2*pi))
}
Any other comments/critiques are welcome (I am learning)

stat_function, though the legend might require calculating both lines outside of ggplot and adding ageom_pathlayer manually, depending on how picky you are about the legend appearance.