Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colour lines by mean of value pairs in ggplot2

Tags:

r

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

like image 312
geotheory Avatar asked Feb 08 '23 01:02

geotheory


1 Answers

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

like image 56
Psidom Avatar answered Feb 20 '23 20:02

Psidom