1

I am having difficulty setting manual colours with ggplotly.

library(ggplot2)
library(plotly)

set.seed(1)
data.frame(x = 1:10, y = rnorm(10)) %>%

  ggplot(aes(x, y, fill = factor(x > 5), alpha = y)) + 
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("red", "blue"))

ggplotly()

I get the error:

Error in setNames(as.numeric(x), c("red", "green", "blue", "alpha")) : 
  'names' attribute [4] must be the same length as the vector [1]

with traceback:

14: setNames(as.numeric(x), c("red", "green", "blue", "alpha"))
13: FUN(X[[i]], ...)
12: lapply(X = X, FUN = FUN, ...)
11: sapply(valz, function(x) {
        x <- setNames(as.numeric(x), c("red", "green", "blue", "alpha"))
        x[["alpha"]] <- x[["alpha"]] * 255
        do.call(grDevices::rgb, c(x, list(maxColorValue = 255)))
    })
10: rgb2hex(x[idx])
9: toRGB(aes2plotly(data, params, "fill"), aes2plotly(data, params, 
       "alpha"))
8: geom2trace.GeomBar(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]])
7: (function (data, params, p) 
   {
       UseMethod("geom2trace")
   })(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]])
6: mapply(FUN = f, ..., SIMPLIFY = FALSE)
5: Map(geom2trace, dl, paramz[i], list(p))
4: layers2traces(data, prestats_data, panel$layout, p)
3: gg2list(p, width = width, height = height, tooltip = tooltip, 
       source = source)
2: ggplotly.ggplot()
1: ggplotly()

What is the correct way to set alpha and fill/colour when using ggplotly? The error is not present when either alpha is not used or the colours are not set manually.

Hugh
  • 15,521
  • 12
  • 57
  • 100

1 Answers1

1

I believe its the alpha = y that's the issue.

library(plotly)

# Generate sample data
df <- data.frame(x = 1:10,
                 y = sample(1:5, size = 10, replace = T),
                 col = sample(LETTERS[1:4], size = 10, replace = T))

First geom_point (works fine)

# ggplot2 syntax
ggplot(df, aes(x, y, color = col, alpha = y)) +
  geom_point()

ggplotly()

enter image description here

Next geom_bar (breaks)

ggplot(df, aes(x, y, fill = col, alpha = y)) +
  geom_bar(stat = "identity")

ggplotly()

enter image description here

Modify geom_bar with alpha as factor instead (works)

ggplot(df, aes(x, y, fill = col, alpha = factor(y))) +
  geom_bar(stat = "identity")

ggplotly()

enter image description here

I believe this has something to do with plotly.js. When alpha is specified as a set of discrete values each bar is plotted as a separate trace with a specified alpha value for the entire trace and not specific markers.

enter image description here

I don't think a continuous set of alpha values is currently supported for bar plots since it does work for scatter plots.

Hope this helps...

royr2
  • 2,239
  • 15
  • 20