As title says the function below that plots a number of densities from the data passed, does not plot the legend. MWE:
plotDensities <- function(xlab="", xlim=c(), ...) {
datas <- list(...)
cbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
if (length(datas) > length(cbPalette)) return(invisible(NULL))
dplot <- ggplot() + xlab(xlab) +
scale_colour_manual(values=setNames(cbPalette[1:length(datas_names)], datas_names)) +
theme(legend.position = c(.8, .8))
datas_names <- names(datas)
for (i in 1:length(datas)) {
name <- datas_names[i]
values <- data.frame(x=datas[[name]])
dplot <- dplot + geom_density(aes(x=x), colour=cbPalette[i], data=values)
}
if (!is.null(xlim))
dplot <- dplot + xlim(xlim)
return(invisible(dplot))
}
v1 <- rnorm(2000, 0, 1)
v2 <- rnorm(3000, 1, 1.5)
v3 <- rnorm(4000, 2, 2.5)
dplot <- plotDensities(xlim="whatever", v1=v1, v2=v2, v3=v3)
dplot