Search code examples
rggvis

Supply a vector of colours to be used in ggvis grouped plot


I would like to use ggvis to achieve what is answered by this similar question: Colouring plot by factor in R

Using the mtcars dataset as an example, and taken from layers: Grouping:

data(mtcars)
mtcars %>% 
  dplyr::mutate(cyl2 = factor(cyl)) %>% 
  ggvis(~wt, ~mpg, stroke = ~cyl2) %>% 
  layer_lines()

produces

ggvis plot with default colours for factor levels

with default factor colours given by stroke = ~cyl2.

How do I change these default colours?


Solution

  • Simply add a stroke scale:

    ... %>%
    scale_ordinal("stroke", range = c("red", "green", "blue"))
    

    Works with hex representations too!

    ... %>%
    scale_ordinal("stroke", range = c("#fc8d59", "#aaaaaa", "#99d594"))