使用alpha和手动颜色与ggplotly

时间:2016-05-28 03:07:14

标签: r plotly

我无法使用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()

我收到错误:

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

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()

使用ggplotly时设置Alpha和填充/颜色的正确方法是什么?如果未使用alpha或未手动设置颜色,则不会出现错误。

1 个答案:

答案 0 :(得分:1)

我认为alpha = y是问题所在。

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))

第一个geom_point(工作正常)

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

ggplotly()

enter image description here

下一个geom_bar(休息)

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

ggplotly()

enter image description here

使用alpha作为因子修改geom_bar(工作)

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

ggplotly()

enter image description here

我认为这与plotly.js有关。当alpha被指定为一组离散值时,每个条形图被绘制为单独的跟踪,其中包含整个跟踪的指定alpha值,而不是特定的标记。

enter image description here

我不认为条形图当前支持一组连续的alpha值,因为它适用于散点图。

希望这会有所帮助......