在 ggplotly 中使用 alpha 和手动颜色 [英] Using alpha and manual colours with ggplotly

查看:77
本文介绍了在 ggplotly 中使用 alpha 和手动颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 ggplotly 手动设置颜色时遇到困难.

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

我收到错误:

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 或未手动设置颜色时,不会出现错误.

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.

推荐答案

我相信 alpha = y 这就是问题所在.

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

第一个 geom_point(工作正常)

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

ggplotly()

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

ggplotly()

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

ggplotly()

我相信这与 plotly.js 有关.当 alpha 被指定为一组离散值时,每个条都被绘制为一个单独的轨迹,并为整个轨迹指定一个 alpha 值,而不是特定的标记.

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.

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

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

希望这有帮助...

这篇关于在 ggplotly 中使用 alpha 和手动颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆