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

6
  • 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". Commented Aug 7, 2015 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. Commented Aug 7, 2015 at 15:44
  • Here's as nice description of the use of group: kohske.wordpress.com/2010/12/27/faq-geom_line-doesnt-draw-lines Commented Aug 7, 2015 at 16:47
  • Also relevant: Plotting lines and the group aesthetic in ggplot2 Commented Aug 7, 2015 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! Commented Aug 8, 2015 at 8:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.