custom colors in R Plotly

前端 未结 4 2028
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 00:57

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

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 01:40

    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
    

提交回复
热议问题