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.