First, we will define some sample data to make a reproducible example
set.seed(15)
dd<-data.frame(x=rep(1:5, 2), y=cumsum(runif(10)),
group=rep(letters[1:2],each=5), other=sample(letters[1:4], 10, replace=T))
Explicit Transformation
I guess if I want to color each segment individually, I'd prefer to be explicit and to the transformation myself. I would do a transformation like
d2 <- do.call(rbind, lapply(split(dd, dd$group), function(x)
data.frame(
X=embed(x$x,2),
Y=embed(x$y, 2),
OTHER=x$other[-1],
GROUP=x$group[-1])
))
And then I can compare plots
ggplot(dd, aes(x,y,group=group, color=other)) +
geom_line() + ggtitle("Default")
ggplot(d2, aes(x=X.1, xend=X.2,y=Y.1,yend=Y.2, color=OTHER)) +
geom_segment() + ggtitle("Transformed")

Reverse Sort + geom_path
An alternative is to use goem_path
rather than geom_line
. The latter has an explicit sort along the x
and it only uses the start point to get color information. So if you reverse sort the points and then use geom_path
to avoid the sort, you have better control of what goes first and therefore have more control over which point the color properties come from
ggplot(dd[order(dd$group, -dd$x), ], aes(x,y,group=group, color=other)) +
geom_path() + ggtitle("Reversed")
