Search code examples
rplotly

Is there a way to make a vectorized alpha in R plotly?


In ggplot you can change the opacity for each point individually: ggplot(iris)+geom_point(aes(x=Sepal.Width, y=Sepal.Length, fill=Petal.Width, color=Petal.Width, alpha=Petal.Length)). Is there a way to do that in plotly as well? This does not work: plot_ly(iris, x=~Sepal.Width, y=~Sepal.Length, color=~Petal.Width, alpha=~Petal.Length) gives

Error in vapply(traces, function(x) x[["alpha"]] %||% 1, numeric(1)) : 
  values must be length 1,
 but FUN(X[[1]]) result is length 150

Solution

  • The first issue is that the opacity is set via the opacity= attribute in plotly not with alpha=. Additionally, the opacity is an attribute of the marker attribute. Finally, you have to convert your values manually to the 0 to 1 range for which I use scales::rescale. Also note, that different to ggplot2 you will not get a legend for the opacity.

    library(plotly)
    
    plot_ly(iris,
      x = ~Sepal.Width, y = ~Sepal.Length, 
      color = ~Petal.Width,
      marker = list(
        opacity = ~ scales::rescale(Petal.Length, to = c(0, 1))
      )
    )