I'm trying to put the legend for my density plot with the theoretical plot in the histogram.
## lambda is 5
lambda <- 5
## the number of simulations is 20,000
nsim <- 20000
## the number of exponentials is 30
n_30 <- 30
## 20,000 simulations are run and a histogram of the results is generated
mns = NULL
for (i in 1 : nsim) {
mns <- c(mns, mean(rexp(n_30, lambda)))
}
hist(mns, col = "grey", main = "Frequency Distribution of Means of 30 Exponentials")
mean(mns)
## load the ggplot2 package
library(ggplot2)
data <- as.data.frame(mns)
## plot histogram with an overlay of the theoretical and sample distribution
plot <- ggplot(data, aes(x = mns))
plot <- plot + geom_histogram(aes(y=..density..), colour="black", fill="white")
plot <- plot + geom_density(aes(color = "Simulated"), size = 1.0, linetype="dashed")
plot <- plot + stat_function(aes(colour = "Normal"), fun = dnorm,
args = list(mean = mean(mns), sd = sd(mns)),
color = "blue",
size = 1.0, show.legend = TRUE)
plot <- plot + labs(title = "Sample vs. Theoretical Distributions of Means of 30 Exponentials",
x = "Means of exponential distributions",
y = "Density") + scale_colour_manual("Lgend title", values = c("red", "blue"))
print(plot)
However, when I run this code in my RMarkdown, the legend for stat_function (Normal) is not showing correctly. Can anybody help on this?
Are you saying that the red isn't appearing on the legend when you run it in RMarkdown? Also, could you please format the code in code chunks? It makes for easier reading!