评论后的改进方法:
由于颜色变得有点棘手(请参阅下面的初始建议),我不得不将整个事情分解并在循环中使用 and 的组合plot_ly()
以add_traces()
确保情节设置不会以错误的顺序应用颜色。下面的情节应该正是您正在寻找的。
阴谋:

请注意,我附加了一个连续的数字列ID
。为什么?因为您希望名称按字母顺序排列,并且行按它们在源中出现的顺序添加到图中。这有点棘手,因为直接订购使用dt %>% arrange((Entity))
会给你Entity1, Enitity10, Entity11
等。如果你想以任何其他方式调整它,请告诉我。
代码:
library(dplyr)
library(plotly)
# data
set.seed(123)
dt <- as.data.frame(matrix(ncol = 13, nrow = 19))
colnames(dt) <- c("Entity", month.abb)
for (i in 1:nrow(dt)) {
dt[i, 1] <- paste("Entity", i, sep="")
dt[i, -1] <- floor(runif(12, min=0, max=100))
}
# assign colors to entities
dt$"EntityColor" <- c("#074263", "#0B5394", "#3D85C6", "#6D9EEB", "#A4C2F4", "#CFE2F3", "#5B0F00", "#85200C", "#A61C00", "#CC4125", "#DD7E6B", "#E6B8AF", "#F8CBAD", "#F4CCCC", "#274E13", "#38761D", "#E06666", "#CC0000", "#20124D")
# sort data
dt$ID <- seq.int(nrow(dt))
dt <- dt %>% arrange(desc(ID))
# specify month as factor variable to ensure correct order
months=names(dt)[2:13]
months<- factor(months, levels = c(months))
# plotly setup
p <- plot_ly(type = 'bar')
# add trace for each entity
nrows = nrow(dt)
for(i in 1:nrows) {
p <- p %>% add_trace(x=months, y = unlist(dt[i,2:13], use.names=F), type = 'bar',
#name = paste(dt[i,1], dt[i,14], sep = "_"),
name = dt[i,1],
type = 'bar',
marker=list(color = dt[i,14])) %>%
layout(barmode = 'stack')
}
# Edit layout
p <- p %>% layout(title = list(xanchor='right', text='Correct colors, orderered legend'),
yaxis = list(title = ''),
xaxis = list(title = 'month'))
p
颜色正确性验证:

初步建议
这是一个初步的建议。首先,color = ~Entity
得走了。而marker = list(color = ~EntityColor)
vsmarker = list(colors = ~EntityColor)
给出了两个不同的结果。更奇怪的是饼图文档使用:
marker = list(colors = colors, ...)
...并且条形图文档使用:
marker = list(color = c('rgba(204,204,204,1)', 'rgba(222,45,38,0.8)', ...)
...没有s
.color
无论哪种方式,您都应该测试两者marker = list(color = ~EntityColor)
,marker = list(colors = ~EntityColor)
看看什么对您来说是正确的。
阴谋:

代码:
dt <- as.data.frame(matrix(ncol = 13, nrow = 19))
colnames(dt) <- c("Entity", month.abb)
for (i in 1:nrow(dt)) {
dt[i, 1] <- paste("Entity", i, sep="")
dt[i, -1] <- floor(runif(12, min=0, max=100))
}
# assign colors to entities
dt$"EntityColor" <- c("#074263", "#0B5394", "#3D85C6", "#6D9EEB", "#A4C2F4", "#CFE2F3", "#5B0F00", "#85200C", "#A61C00", "#CC4125", "#DD7E6B", "#E6B8AF", "#F8CBAD", "#F4CCCC", "#274E13", "#38761D", "#E06666", "#CC0000", "#20124D")
data.table::melt(dt) %>%
plot_ly(x = ~variable,
y = ~value,
name= ~Entity,
type = "bar",
#color = ~Entity,
marker = list(colors = ~EntityColor)
) %>%
layout(yaxis = list(title = ""),
xaxis = list(title = ""),
barmode = 'stack')
看看它是如何为你工作的。