2

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!

deepsky
  • 121
  • 4
  • 3
    Don't use loops; `melt` or `gather` your data into long format. – Gregor Thomas Jan 21 '16 at 21:08
  • 1
    Possible dupe: http://stackoverflow.com/q/17150183/903061 – Gregor Thomas Jan 21 '16 at 21:08
  • 1
    +1 to @Gregor. `melt` and `ggplot` go together like ham and cheese. Once your data are melted, identify your group in the aesthetics: `aes(group = variable)` – oshun Jan 21 '16 at 23:39
  • Thanks @Gregor. `melt` was the way to go. That other post was similar, but using a for loop was able to achieve the various line plots, with just the legend items absent. Either way, `melt` is the way to go . Ham and cheese indeed. I'm new to ggplot, and so far it seems powerful, but definitely takes getting used to. – deepsky Jan 22 '16 at 00:26
  • Give ggplot a few months and you'll never look back ;) – Gregor Thomas Jan 22 '16 at 07:25

0 Answers0