Search code examples
rggvis

Is it possible to apply variation to properties in ggvis


I would like to vary the opacity of a bar dependent on a variable

library(dplyr)
library(ggvis)
df <- data.frame(x=c(1,2),y=c(6,3),op=c(0.2,0.8))

df %>%
  ggvis(x=~x,y=~y) %>%
  layer_bars(opacity:=~op)

produces error

Error in eval(expr, envir, enclos) : object 'op' not found

Solution

  • This seems to work....

    df %>%
      ggvis(x=~x,y=~y, fillOpacity :=~ df$op) %>%
      layer_bars()
    

    It produces this:

    enter image description here

    It's basically equivalent to doing this:

    df %>%
      ggvis(x=~x,y=~y, fillOpacity :=~ c(0.2,0.8)) %>%
      layer_bars()
    

    and works because there is one value assigned to each y-variable. I'm not sure why the following doesn't work, it seems to me it should. Perhaps somebody can enlighten...

    df %>%
      ggvis(x=~x,y=~y, fillOpacity :=~ op) %>%
      layer_bars()
    

    Alternatively, using your code, if you do this ...

    df %>%
      ggvis(x=~x,y=~y) %>%
      layer_bars(opacity:=~df$op)
    

    then you remove the remove the border of the bar as everything is colored with the opacity color...

    enter image description here