R - discrete colors for continuous data in ggplot

I am trying to plot some temporary data. I applied a simple algorithm that assigns a discrete number ( state

) to each row of 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 a stream for example (using ggplot

) and <<20> define the color. The problem is, if I do

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

      

The subject has too little color contrast to be easily distinguished 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 breaks the lines and they show up as three different lines. I would like to use a continuous scale, but add one or more intermediate colors for contrast. The current solution is

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 must be NA

, 2) excludes one of the states ( NA

) from the legend, and 3) displays unused values ​​in the legend.

Image produced by the current code: Current output

+3


source to share





All Articles