Varun
Varun

Reputation: 1321

R Plotly change color of stacked bar chart

I have a Plotly stacked bar plot. I'd like to change the colors of the bars so I have Red and Dark Blue instead of the default colors you see below

enter image description here

My code below. I tried using the marker function but it converts the whole plot to a single color. Any help would be appreciated.

pie_subsegment_split %>%
plot_ly(x = ~Segment, y = ~Not*100, type = 'bar', name = 'Not') %>%
add_trace(y = ~QoL*100, name = 'QoL') %>%
layout(yaxis = list(title = 'Percentage (%)'),barmode = "stack",showlegend=T) %>%
layout(xaxis = list(title="Sub-Segment",showticklabels=FALSE))

Upvotes: 4

Views: 5407

Answers (1)

Ameya
Ameya

Reputation: 1730

marker works as expected, you only need to specify it for each trace. I suspect inheritance might be at play if you provide only one colour. Try the following -

library(plotly)
set.seed(1)
y1 <- runif(10, 5, 10)
set.seed(5)
y2 <- runif(10, 5, 10)
x <- 1:10
plot_ly(x = x, y = y1, type = 'bar', name = 'QoL', marker = list(color = 'red')) %>% 
  add_trace(y = y2, name = 'not', marker = list(color = 'blue')) %>% 
  layout(
    barmode = 'stack', yaxis = list(title = 'Percentage (%)'), 
    xaxis = list(title = 'Sub-Segment', showticklabels = FALSE)
  )

You should get the following - enter image description here

Upvotes: 9

Related Questions