5

I'm trying to plot some time-continuous data. I have applied a simple algorithm that assigns a discrete number (state) to each row of the data. It looks something like this.

time   flow    pre    state
0.0    0.0     3      1
0.2    0.01    4      1
0.4    0.10    10     2
0.6   -0.11    -2     0      # Set as NA in the example below

Now, I want to plot for instance flow (using ggplot) and have state determine the colour. Problem is, if I do

ggplot(data) +
  geom_line(aes(x = time, y = flow, color = state))

The plot has too little contrast in the colours to easily differentiate state. But if I do

ggplot(data) +
  geom_line(aes(x = time, y = flow, color = factor(state))) +
  scale_color_manual(values = c("red", "green", "blue"))

it splits the lines and they appear as three different lines. What I would like to is to use the continuous scale, but add one or several intermediate colours for contrast. Current solution is this

ggplot(data = alg1) +
  geom_line(aes(x = time, y = flow, colour = state)) +
  scale_color_gradient(low = "#0000FF", high = "#FF0000",
                       na.value = "#00FF00", guide = "legend")

But this 1) only works for three states, and one of them has to be NA, 2) excludes one state (NA) from legend and 3) displays not-used values in legend.

Image produced by current code: Current output

T'n'E
  • 598
  • 5
  • 17
  • 1
    Use `geom_line(aes(group = 1, ...` to avoid one line per level of the variable to which you map `color`. In addition, make sure to provide example data that _could_ give you the desired output _if_ you had the correct code. I.e. you need (at least) one more point for "state = 2". Also, your `scale_color_manual` seem to correspond to three "states". – Henrik Aug 07 '15 at 15:44
  • 1
    Use `aes(x = time, y = flow, color = factor(state), group = 1)` to prevent having separate lines drawn when converting `state` to a factor. See `?aes_group_order` for more about how the group aesthetic works. – TJ Mahr Aug 07 '15 at 15:44
  • Here's as nice description of the use of `group`: https://kohske.wordpress.com/2010/12/27/faq-geom_line-doesnt-draw-lines/ – Henrik Aug 07 '15 at 16:47
  • Also relevant: [Plotting lines and the group aesthetic in ggplot2](http://stackoverflow.com/questions/10357768/plotting-lines-and-the-group-aesthetic-in-ggplot2) – Henrik Aug 07 '15 at 16:53
  • Thanks for the input guys! Left my computer at work, so I can't verify until monday, but this sure looks like what I'm needing! – T'n'E Aug 08 '15 at 08:42
  • Yep, this all works great! If someone will just post this as an answer I can mark it as accepted. – T'n'E Aug 10 '15 at 06:28

1 Answers1

4

Answered in comments:

Grouping via aes(x = time, y = flow, color = factor(state), group = 1) prevents having separate lines drawn when converting state to a factor.

Roman
  • 4,744
  • 2
  • 16
  • 58