I have the following function:
histograms <- lapply(names(stock_markets[2:ncol(stock_markets)]),
function(n){
ggplot(data = stock_markets, aes_string(x = n)) +
geom_histogram(aes(y =..density..), color = "darkblue", fill = "lightblue") +
stat_function(
fun = dnorm,
args = with(stock_markets, c(mean = mean(stock_markets$`n`), sd = sd(stock_markets$`n`)))) +
scale_x_continuous(n) +
ggtitle(paste("Histogram of", n, "with Normal Curve")) +
xlab(names(n) +
theme(axis.title.y = element_blank(),
axis.line.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()) +
theme(plot.title = element_text(hjust = 0.5))
})
which basically plots the histograms from the dataframe stock_markets
. Each column contains a stock price. My issue is that I used aes_string
to get the names of the columns so that I could use them in aes
but I can't figure out how to use the mean()
and sd()
functions with the n
argument (which is the column I need) so that I can superimpose the normal distribution on the histogram.
I have tried:
mean(n)
mean(stock_markets[n])
mean(stock_markets$`n`)
mean(stock_markets$"n")
but nothing seems to work.
Any help would be greatly appreciated.