I'm trying to use ggplot within a for loop to plot a series of lines (time-series of streamflow values). However, I can't get the legend items to cooperate. My data frame has a date field and 3 fields of streamflow values, and looks like this:
tail(df)
Date StrGage1 StrGage2 StrGage3
1821 2005-12-26 2.8 1449 256
1822 2005-12-27 6.6 775 63
1823 2005-12-28 8.0 1304 159
1824 2005-12-29 7.4 908 70
1825 2005-12-30 7.3 711 58
1826 2005-12-31 76.0 1074 838
I merely want to plot the date on the x-axis, with 3 lines on the y, each of which I need to have its own legend item. However, I keep getting an output that only has a legend item for the last one. The line colors are also not behaving. My code so far is this:
col <- c('coral1','palegreen2','deepskyblue')
plot <- ggplot(df, aes(Date))
for (i in 1:3)
{
plot <- plot + geom_line(aes_string(y = colnames(df)[i+1]), size = 0.2) + aes(color = colnames(df)[i+1]) + geom_area(aes_string(y = colnames(df)[i+1]), fill = col[i], alpha = 0.3)
}
plot <- plot + scale_y_log10(breaks = c(1, 10, 100, 1000, 10000), labels = c(' ','10',' ','1000',' '), limits = c(1,10000))
plot <- plot + labs(x = "", y = "CFS") + scale_colour_manual(name='', values= col[1:3])
with output looking like this: Output Graph
I know it may be easy to skip the for loop and plot each line manually, but for other reasons I need to have it set up in loop form, so my questions are as follows:
1) How can I can the legend items from each loop iteration to be preserved on the plot, and not just the last one? 2) Why are the line colors not corresponding to my scale_colour_manual assignment of the colors from the col vector?
Thanks!