geotheory
geotheory

Reputation: 23650

Colour lines by mean of value pairs in ggplot2

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)?

Upvotes: 4

Views: 174

Answers (2)

akuiper
akuiper

Reputation: 214957

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

Upvotes: 4

Richard Telford
Richard Telford

Reputation: 9923

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)

Upvotes: 4

Related Questions