Search code examples
rggvis

Color path segments in ggvis / layer_paths


I have multiple paths with multiple segments. How does one color the Nth segment of each path with the same color?

For example:

require(dplyr)
require(ggvis)
df <- data.frame(x = runif(10,0,10), y = runif(10,0,10), 
                 group=c(rep(5,5),rep(10,5)), colorIdx=rep(c(1:5), 2))
df$group = factor(df$group)

color_fun = colorRampPalette(c("yellow","blue"),5)

myColors = color_fun(5)

df$color = myColors[df$colorIdx]

df %>% group_by(group) %>% 
  ggvis(~x, ~y, strokeWidth:=~group) %>% layer_paths(stroke :=~color)

The resulting paths are monochromatic - I'd like them to scale from yellow to blue.

enter image description here

Using ggplot2, this can be accomplished with:

require(ggplot2)
ggplot(df, aes(x=x, y=y, group=group, colour=colorIdx, size=group)) + geom_path() +
  scale_colour_gradient("", low="#FED863", high="#2A6EBB", limits=c(1,4))

enter image description here


Solution

  • The constraint seems to be that all the segments in the data's group_by groups need to be the same colour. You can get around it by creating an artificial group for each segment, each group only connecting two points. This means you have to double up each row in your data apart from the first and final rows of each of your original groups. I've illustrated this by hand choosing the rows with your data; there would be a way to do it more programmatically but whether this is worthwhile depends on your real use case.

    It's a bit of a bother but certainly a workaround of sorts.

    df2 <- df[c(1,2,2,3,3,4,4,5,    6,7,7,8,8,9,9,10), ]
    df2$group2 <- c(rep(letters[1:4], each=2), rep(letters[6:9], each=2))
    
    df2 %>% group_by(group2) %>% 
       ggvis(~x, ~y, strokeWidth:=~group) %>% 
       layer_paths(stroke :=~color)
    

    enter image description here