Color path segments in ggvis / layer_paths

I have several paths with multiple segments. How does one color of the Nth segment of each path have one 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 would 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

+8
r ggvis
source share
1 answer

It seems that the limitation is that all segments in group_by data groups should be the same color. You can get around this by creating an artificial group for each segment, with each group connecting only two points. This means that you need to double each line in your data, except for the first and last lines of each of your source groups. I illustrated this manually by selecting the rows with your data; there would be a way to do this more programmatically, but whether it is worth it depending on your actual use.

A little worry, but of course, a workaround.

 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

+5
source share

All Articles