0

In theory I assign a color attribute to geom_line, there are two data points from which the color could be assigned. In practice, ggplot2 seems to be taking the first point's value and carrying it forward as the line's color. Is there a way to use the second point's attribute value to assign the color instead of the first one?

ggplot(data, aes(x = timeVal, y = yVal, group = groupVal, color = colorVal)) + geom_line()
daj
  • 6,962
  • 9
  • 45
  • 79
  • In theory, when plotting a line, the value you choose to use to color the line should be the same for all points in the line. Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that has sample input data that is relevant to your problem. Also, if you're thinking of a line as having only two points, perhaps `geom_segment()` is more appropriate? But still that assumes only one value for color for both points. – MrFlick Sep 03 '14 at 01:14
  • "color the line should be the same for all points in the line" - this is not true in ggplot2 since color is an independent parameter of group. geom_line() is what I intend - the line has more than two points, but any geom_line() is necessarily comprised of line segments. – daj Sep 03 '14 at 01:38
  • I see what you're saying now. Still, a reproducible example would go a long way – MrFlick Sep 03 '14 at 01:50

1 Answers1

0

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

enter image description here

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

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295