I\'m currently a beginner in Plotly and have a problem I can\'t seem to solve. I have my plotly stacked bar chart but I don\'t know how to color each individual category. I
Here's something that might help. Note that for some reason, Method 1 causes the legend entries to be black. So I am also suggesting a workaround.
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