I have the following script:
library(ggplot2)
values <- c(0.1,0.15,0.2,0.3,0.5,1,1.5,2,2.5)
colours <- palette()[1:length(values)];
p <- ggplot(data.frame(x=c(0, 2)), aes(x)) +
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 0.1),aes(colour="0.1"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 0.15),aes(colour="0.15"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 0.2),aes(colour="0.2"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 0.3),aes(colour="0.3"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 0.5),aes(colour="0.5"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 1),aes(colour="1"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 1.5),aes(colour="1.5"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 2),aes(colour="2"))+
stat_function(fun= function(x) dlnorm(x,mean = 0, sd = 2.5),aes(colour="2.5"))+
scale_colour_manual("Sigma:", values=colours, breaks=as.character(values))
p
Which produces the following graph (minus the title) of how the log-normal distribution looks like for different values of a parameter:
How can I replace those copy-pasted lines with something more eye-friendly?
Something like stat_function(fun= function(x) dlnorm(x,mean = 0, sd = values),aes(colour=as.character(values)))
Edit: Unlike the question that was suggested as duplicate, I'm handling functions, not data, so I'm not sure how to apply the suggestions there
I also tried in a for-loop like this:
library(ggplot2)
values <- c(0.1,0.15,0.2,0.3,0.5,1,1.5,2,2.5)
colours <- palette()[1:length(values)];
p <- ggplot(data.frame(x=c(0, 2)), aes(x)) +
ggtitle(expression(paste("Log-normaal distributie met verschillende waarden van ", sigma)))+
ylab(expression(paste(f[X](x))))
for(i in 1:length(values)){
p <- p + stat_function(fun= function(x) dlnorm(x,mean = 0, sd = values[i]), aes(colour=as.character(values[i])))
}
p + scale_colour_manual("Sigma:", values=colours, breaks=as.character(values))
But it doesn't work: it only plots the last curve.
I also tried as the an answer suggested, which works fine, but I'm then unable to add labels to the colours:
ggplot(data.frame(x=c(0, 2)), aes(x)) +
mapply(function(col, mean, sd) {
stat_function(fun = dlnorm, args = list(mean = mean, sd = sd), aes(colour=col))},
mean = 0, sd = values, col = as.character(values)) +
scale_colour_manual("Sigma:", values=colours, breaks=as.character(values))
It produces an error saying:
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 2