0

I am plotting a ggvis graph with different colors and linetype by setting stroke and strokeDash parameters. The colors are not showing what I want, for ex: I need "red", "blue" and "green" colors where as the colors shown are " blue", "orange" and "green".(code example and screenshot are below).

I also need to add legend based on the color and linetype. I am unable to add the legend combining both "color type"(stroke) and "line type"(strokeDash).

Below is a sample code I am working.

mydf <- data.frame(xval = c(1:5),USA = c(11:15), Canada = c(21:25), UK = c(31:35))

mydf2 <- tidyr::gather(mydf, 'var', 'val', -xval)

mydf2$mycol <- c(rep("Red",5), rep("Blue",5), rep("Green",5))
mydf2$mydash <- c(rep(5,5), rep(-1,5), rep(10,5))

myggv2 <- mydf2 %>% ggvis(x = ~xval, y = ~val, stroke = ~mycol,      
strokeDash := ~mydash) %>% layer_points(size := 100) %>%
add_tooltip(function(d) { paste0("x:", d$xval, "<br>", "y:", d$val) }, "hover") %>% group_by(var) %>% 
layer_paths() %>% add_axis("x", title = "qtrs") %>% 
  add_axis("y", title = "MEV")%>% hide_legend("stroke")
myggv2

Here is the screenshot of the graph.Screenshot

Thanks

2
  • For the main color question you are just missing := to set colors instead of map colors. See the answer here. If I wanted a legend, though, I might map var to stroke and then change the colors using scale_nominal. There is currently no strokeDash legend available. See here.
    – aosmith
    Commented Jun 10, 2016 at 15:13
  • Thanks @aosmith for your suggestion. could you please write the code for the same. I am still new to ggvis plotting.
    – user98180
    Commented Jun 11, 2016 at 21:56

1 Answer 1

0

You can change colors in your plot and legend for discrete variables using scale_nominal.

In this approach, you map the variable you want in the legend within the plotting code and then change away from the default colors using your chosen colors. I'm using var for the stroke variable in this example.

mydf2 %>%
    ggvis(x = ~xval, y = ~val, stroke = ~var,      
          strokeDash := ~mydash) %>% 
    layer_points(size := 100) %>%
    add_tooltip(function(d) { paste0("x:", d$xval, "<br>", "y:", d$val) }, "hover") %>% 
    group_by(var) %>% 
    layer_paths() %>% 
    add_axis("x", title = "qtrs") %>% 
    add_axis("y", title = "MEV") %>%
    scale_nominal("stroke", label = "Country", range = unique(mydf2$mycol))

enter image description here

Note that at this time ggvis does not support a strokeDash legend. See this open github issue.

Not the answer you're looking for? Browse other questions tagged or ask your own question.