Search code examples
rggvis

Named colors in R and ggvis


I have encountered a problem with R's named colors when I use the ggvis package. For example, if I set the ggvis fill property to "cadetblue" it works, but if I set it to "cadetblue1" it does not. Here is a small reproducible example:

library(ggvis)
pressure %>% ggvis(~temperature, ~pressure, fill := "cadetblue") %>% layer_bars()

When I change the fill property to "cadetblue1" the plot turns black. It seems only the major named colors without a number in the name works when using ggvis. Does anybody know why or have I misunderstood something here?


Solution

  • I don't know why that's happening, but you can use the named colors by converting from name to hexadecimal.

    • col2rgb converts the color name to its 8-bit numeric rgb values (rendered in base 10).
    • rgb takes the output of col2rgb (after conversion from a column vector to a row vector using t (transpose)) and converts them to the corresponding hexadecimal color code.

    So, in your case, the code would be:

    fill := rgb(t(col2rgb("cadetblue1")), maxColorValue=255)
    

    Or, to see the individual steps:

    x = t(col2rgb("cadetblue1"))
    
         red green blue   
    [1,] 152   245  255
    
    rgb(x, maxColorValue=255)
    
    [1] "#98F5FF"