I want to plot lines for separate data frames in the same graphic with a different color for each data frame. I can get a legend using almost the same code and aes(colour = "hard-coded-name") but I don't know the names ahead of time. I don't have enough RAM to rbind the data frames into a single data frame. I've written a sample that produces the plot with the colored lines. How do I add a legend? As in the sample, you don't know ahead of time how many data frames are in the list (ldf) or what their names are.
library('ggplot2')
f30 <- function() {
###############################################################
##### Create a list with a random number of data frames #######
##### The names of the list elements are "random" #######
###############################################################
f1 <- function(i) {
b <- sample(1:10, sample(8:10, 1))
a <- sample(1:100, length(b))
data.frame(Before = b, After = a)
}
ldf <- sapply(1:sample(2:8,1), f1, simplify = FALSE)
names(ldf) <- LETTERS[sample(1:length(LETTERS), length(ldf))]
palette <- c(
"#000000", "#E69F00", "#56B4E9", "#009E73",
"#F0E442", "#0072B2", "#D55E00", "#CC79A7"
)
###############################################################
##### Above this point we're just creating a sample ldf #######
###############################################################
ePlot <- new.env(parent = emptyenv())
fColorsButNoLegend <- function(ix) {
df <- ldf[[ix]]
n <- names(ldf)[ix]
if (ix == 1) {
ePlot$p <- ggplot(df, aes(x = Before, y = After)) +
geom_line(colour = palette[ix])
} else {
ePlot$p <- ePlot$p +
geom_line(
colour = palette[ix],
aes(x = Before, y = After),
df
)
}
}
sapply(1:length(ldf), fColorsButNoLegend)
#Add the title and display the plot
a <- paste(names(ldf), collapse = ', ')
ePlot$p <- ePlot$p +
ggtitle(paste("Before and After:", a))
ePlot$p
}

