这里有一些可能会有所帮助的东西。请注意,由于某种原因,方法 1 会导致图例条目为黑色。所以我也建议一种解决方法。
library(plotly)
library(dplyr)
library(data.table)
mtcars$color <- factor(mtcars$gear, labels = c("blue", "red", "green"))
# Method 1
# Legend entries are all black
plot_ly(mtcars, x = as.factor(cyl), y = mpg, group = gear, type = "bar", marker = list(color = color), name = "test") %>%
layout(barmode = "stack", showlegend = T)
# Method 2
# Workaround
dt <- data.table(mtcars)
p <- dt[gear == 3,] %>%
plot_ly(x = factor(cyl), y = mpg, name = "Gear = 3", type = "bar", marker = list(color = "blue"))
p <- dt[gear == 4,] %>%
add_trace(x = factor(cyl), y = mpg, name = "Gear = 4", type = "bar", marker = list(color = "red"))
p <- dt[gear == 5,] %>%
add_trace(x = factor(cyl), y = mpg, name = "Gear = 5", type = "bar", marker = list(color = "green"))
p <- layout(p, barmode = "stack")
p