Search code examples
rr-plotly

Plotly not updating the second color in R


I am trying to plot a basic donut plot in R using plotly. I then add custom colors to the plot. Now, the first color updates fine, but the second color i.e. 'rgb(255,127,80)' doesn't.

How can I fix this?

Data

Value = c(50124,  9994,  9822, 13580,  5906,  7414, 16847,    59, 80550,  6824,  3111, 16756,  7702, 23034, 38058,  6729,  6951,     2,   408,
 37360, 20517, 18714,   352,     3, 42922, 30850,    21,  4667, 12220,  8762,   445,  1875,   719,   188,    26,   124,   996,    10,
    27,   304,    55, 34980,    67,     3,    25,  1012,  3588,    77,   847,    47,  1057,   924,   233,    40,     2,  2362,     3,
  1866,    16,     0,     0,     0)

Type = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A",  "A", 
"B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B",  "B", 
"B",  "B",  "B",  "B",  "B" "B", "B",  "B",  "B",  "B",  "B", 
"B",  "B",  "B",  "B",  "B",  "B",  "B")

df = data.frame(Type, Value)

Code

library(tidyverse)
library(plotly)

color = c('rgb(0,255,255)', 'rgb(255,127,80)')

fig = df %>% plot_ly(labels = ~Type, 
                        values = ~Value,
                        #colors = c("grey50", "blue"),
                        marker = list(colors = color)
                        )
fig = fig %>% add_pie(hole = 0.6)
fig = fig %>% layout(title = "Title",  showlegend = T,
                      xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T),
                      yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = T))

fig

Current output

enter image description here


Solution

  • You could it this way: Note: 1. make a column in your dataframe for the colors 2. use type=pie with add_pie(hole=0.4)

    df1 <- df %>% 
      group_by(Type) %>% 
      mutate(sum = sum(Value),
             Typecolor = ifelse(Type=="A", 'rgb(0,255,255)', 'rgb(255,127,80)'))
    
    df1 %>% plot_ly(labels = ~Type, 
                   values = ~Value,
                   type = 'pie',
                   textposition = "inside",
                   textinfo = 'label+percent',
                   hole=0.6,
                   marker = list(colors = ~Typecolor)
                   ) %>% add_pie(hole = 0.4)
            )
    

    enter image description here