4
votes

When mapping colour to lines in ggplot2, e.g.:

x = data.frame(x = 1:6, y = c(0,0,10,10,0,0))
ggplot(x, aes(x, y, col=y)) + geom_line(size=5)

enter image description here

.. the lines colours are mapped to the first data point of each line segment. Is there any easy way to get ggplot to calculate the mean value of both points instead (ie. so the sloping lines are both scaled to the colour for 5)?

2
What about calculating average values between two points and use that column to assign colors? - jazzurro
Sure, but that gets tricky when subsetting for multiple lines, and depending on your data structure. Guess I'm being lazy, but I'm just wonder if there's a ggplot solution.. - geotheory
With the given data, the two answers are doing the job, I think. temp <- mutate(x, foo = (lead(y, default = 0) + y) / 2); ggplot(temp, aes(x = x, y = y, col = foo)) + geom_line(size=5) would do the same job. If you have more complicated situation, I think it is worth adding more description in your question. - jazzurro

2 Answers

4
votes

Similar idea as @Richard, but use the zoo package.

library(zoo)
x = data.frame(x = 1:6, y = c(0,0,10,10,0,0))
ggplot(x, aes(x, y, col=rollmean(y, 2, fill = 0))) + geom_line(size=5)

enter image description here

4
votes

Does this do what you want?

x = data.frame(x = 1:6, y = c(0,0,10,10,0,0))
x$c <- rowMeans(cbind(x$y, c(x$y[-1], NA)))
ggplot(x, aes(x, y, col=c)) + geom_line(size=5)