颜色数 = 类别数的 plotly 条形图

plotly bar chart with number of colors = number of categories

对于以下对象:

rawData <-
structure(list(obs = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), key = structure(1:8, .Label = c("sadness", 
"neutral", "contempt", "disgust", "anger", "surprise", "fear", 
"happiness"), class = "factor"), value = c(2.36220472440945, 
89.3700787401575, 0.393700787401575, 0.78740157480315, 0, 0.78740157480315, 
0, 6.2992125984252)), .Names = c("obs", "key", "value"), row.names = c(NA, 
8L), class = "data.frame")

我想创建一个绘图条形图,同时为每个条形指定颜色。 不幸的是,它只会采用 n-1 种颜色,为剩余的颜色创建自己的 "gradient"。

rawData %>% 
    group_by(obs) %>%
    plot_ly(x = obs, 
            y = value, 
            type = "bar", 
            color = key,
            colors = c("blue","grey","darkred","green","orange","black","purple"))

如果我尝试添加第 8 种颜色...

rawData %>% 
        group_by(obs) %>%
        plot_ly(x = obs, 
                y = value, 
                type = "bar", 
                color = key,
                colors = c("blue","grey","darkred","green","orange","black","purple","yellow"))

现在所有的条都是黄色的。

作为替代方案,您还可以使用 ggplot2 在 plotly 中生成一个图,这将为您提供所需的内容。

p <- ggplot(data=rawData, aes(x=obs, y=value, color=key, group=key, fill=key)) + geom_bar(stat='identity', position='dodge') + scale_fill_manual(values=c("blue","grey","darkred","green","orange","black","purple","yellow")) + scale_color_manual(values=c("blue","grey","darkred","green","orange","black","purple","yellow"))

ggplotly(p)

使用 color 参数代替 marker 参数。

rawData %>% 
  group_by(obs) %>%
  plot_ly(x = obs, 
    y = value, 
    type = "bar", 
    color = key,
    marker = list(color=c("blue","grey","darkred","green","orange","black","purple","yellow")))