rplotlysunburst-diagram

Unable to display correct colors in plotly sunburst plot


I am trying to make a sunburst figure using plotly in R. However, I can't get the colors to display properly.

This is my code:

library(plotly)
test <- data.frame(
  stringsAsFactors = FALSE,
  ids = c("pH", "SpecificConductance","TotalNitrogen","TotalPhosphorous","OE_Macroinvertebrate",
          "PctBankOverheadCover","PctFinesLessThan2mm","PctBankCovered","PctBankStable",
          "FloodplainConnectivity","WaterQuality","Biodiversity","WatershedFunction",
          "SiteScore"),
          
  labels = c("pH<br>A",
             "SpecificConductance <br> A", "TotalNitrogen <br> A","TotalPhosphorous <br> F",
             "OE_Macroinvertebrate <br> B", "PctBankOverheadCover <br> B",
             "PctFinesLessThan2mm <br> A","PctBankCoveredMIM <br> B",
             "PctBankStable <br> A","FloodplainConnectivity <br> F",
             "WaterQuality <br> B","Biodiversity <br> B",
             "WatershedFunction <br> B", "SiteScore <br> B"),
  parents = c("WaterQuality", "WaterQuality","WaterQuality",
              "WaterQuality","Biodiversity","Biodiversity","WatershedFunction","WatershedFunction",
              "WatershedFunction","WatershedFunction","SiteScore","SiteScore",
              "SiteScore",
              NA ),
  colors = c("#481567FF","#481567FF","#481567FF","#FDE725FF","#238A8DFF","#238A8DFF",
    "#481567FF","#238A8DFF","#481567FF","#FDE725FF","#238A8DFF","#238A8DFF","#238A8DFF",
    "#238A8DFF"
  )
)

test_plot <- plot_ly(test, ids = ~ids, labels = ~labels, parents = ~parents, 
                       type = 'sunburst'
) %>% layout(colorway = ~colors)

test_plot

This is the output I get. However, these are not the colors my code is specifying: there should be a mixture of purple, teal and yellow and the center should be colored as well. Any idea how to fix the color display? I am using R version 4.4.0

sunburst

snippet of code with colors

I have tried working through examples on stack overflow (Plotly sunburst coloring) and can replicate the examples but when I replace with my data it doesn't work properly


Solution

  • To achieve your desired result set the colors via the marker= attribute of the trace. This way you can set a color for each sector of the sunburst. Using colorway= you only set the default colors from which plotly will pick the colors based on the number of parent categories, i.e. it will pick the first 3 colors from your vector of colors.

    library(plotly)
    
    plot_ly(test,
      ids = ~ids, labels = ~labels, parents = ~parents,
      marker = list(
        colors = ~colors
      ),
      type = "sunburst"
    )