Search code examples
rplotlycolor-scheme

plotly - how to make a bar chart and a pie chart share the same color code


How can we make the two plots below share the same colors for each category?

plot_ly(data = mtcars, labels = ~carb, values = ~mpg, type = 'pie')

plot_ly(mtcars, x = ~mpg, y = ~gear, type = 'bar', name = ~carb)

Have tried the below but it didn't work.

pal <- c("red", "blue", "green", "yellow", "orange", "violet", "brown", "pink", "lavender")
plot_ly(data = mtcars, labels = ~carb, values = ~mpg, type = 'pie', color = ~carb, colors = pal)

plot_ly(mtcars, x = ~mpg, y = ~gear, type = 'bar', name = ~carb, color = ~carb, colors = pal)

Other answers have suggested explicitly defining the color for each category, but since my data is dynamic (i.e. different for each user), I cannot do that.


Solution

  • Here is the method I used. We know that the pie chart orders the colors by the most common, i.e. largest percentage/largest value being blue, then orange, then green, then red, and so on. So we imitate that order in our bar chart. It is easier to understand with the Iris dataset:

    plotlyDefaultColors <- c("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf")
    
    counts <- iris$Species %>% table()
    
    sortedCounts <- sort(counts, decreasing = TRUE)
    
    codes <- names(sortedCounts)
    
    shortenedListofColors <- plotlyDefaultColors[1:length(codes)]
    
    palette <- setNames(shortenedListofColors, codes)
    
    plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = 'bar', name = ~Species, color = ~Species, colors = palette) %>%
      layout(barmode = 'stack')