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.

geom_line(aes(group = 1, ...to avoid one line per level of the variable to which you mapcolor. 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, yourscale_color_manualseem to correspond to three "states".aes(x = time, y = flow, color = factor(state), group = 1)to prevent having separate lines drawn when convertingstateto a factor. See?aes_group_orderfor more about how the group aesthetic works.group: kohske.wordpress.com/2010/12/27/faq-geom_line-doesnt-draw-lines